An extension Method to Encode Strings

For a project I needed a method to Encode strings. I needed multiple modes, for example HtmlEncode but also some proprietary ones. To keep this as simple as possible, I wrote an extension method and an enum holding the possible modes. The function then decides which actual encoding function to pick (the signature needs to be string FunctionName(string input)) and invokes it.

This abridged example contains two functions: One for Html Encoding and one dummy function that just returns the string. You can easily extend this if needed.

public enum StringEncodeMode
{
    None,
    HtmlEncode
}

public static class StringExtensions
{
    public static string Encode(this string input, StringEncodeMode encodeMode)
    {
        Func<string, string> encodeFunc;
        switch (encodeMode)
        {
            case StringEncodeMode.HtmlEncode:
                encodeFunc = x => HttpUtility.HtmlEncode(x);
                break;
            case StringEncodeMode.None:
            default:
                encodeFunc = x => x;
                break;
        }
        return encodeFunc(input);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *