StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), "Active", true);
Enum.TryParse("Active", out StatusEnum myStatus);
string str = "Dog";
Animal animal = (Animal)Enum.Parse(typeof(Animal), str); // Animal.Dog
Animal animal = (Animal)Enum.Parse(typeof(Animal), str, true); // case insensitive
MyEnum enumValue = Enum.Parse<MyEnum>(stringValue);
using System;
Enum.tryParse("input", out EnumName myEnum);
public static T ToEnum<T>(this string value, T defaultValue)
{
if (string.IsNullOrEmpty(value))
{
return defaultValue;
}
T result;
return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}
/// 09/14/2022 Mahesh Kumar Yadav. <br/>
/// <summary>
/// Convert string to enum
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static T ToEnum<T>(this string value)
{
return (T)Enum.Parse(typeof(T), value, true);
}
public static TEnum ParseEnum<TEnum>(string value) where TEnum : struct
{
TEnum tmp;
if (!Enum.TryParse<TEnum>(value, true, out tmp))
{
tmp = new TEnum();
}
return tmp;
}