ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ToEnum

Convert a String Value to Corresponding Enum Value

Source

public static T ToEnum<T>(this string value, T defaultValue) where T : struct
{
    if (string.IsNullOrEmpty(value))
    {
        return defaultValue;
    }

    T result;
    return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}

Example

public enum Animal{

Cat,
Dog,
Unknown
}


var getEnumValue="Animal".ToEnum<Animal>(Animal.Unknown);

Author: Anonymous

Submitted on: 27 apr. 2016

Language: C#

Type: Generic

Views: 6652