ToEnum

  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);

Description

Convert a String Value to Corresponding Enum Value

Details

  • Author: Anonymous
  • Submitted on: 4/27/2016 2:03:23 PM
  • Language: C#
  • Type: Generic
  • Views: 2161

Double click on the code to select all.

 

;