To convert a string to an enum in C#, you can use the Enum.Parse() method. Here's an example:
Suppose you have an enum defined like this:
xxxxxxxxxx
enum Color
{
Red,
Green,
Blue
}
//And you have a string variable containing the name of the enum value you
//want to convert to, like this:
string colorName = "Green";
//You can convert this string to an enum value like this:
Color color = (Color)Enum.Parse(typeof(Color), colorName);
//This will parse the string colorName as a member of the Color enumeration and assign it to the color variable.
//Note that Enum.Parse() is case-sensitive, so if the string does not match the name of an enum
//member exactly, it will throw an exception. You can use the Enum.TryParse() method to avoid the exception and handle
//errors more gracefully.
xxxxxxxxxx
StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), "Active", true);
xxxxxxxxxx
string str = "Dog";
Animal animal = (Animal)Enum.Parse(typeof(Animal), str); // Animal.Dog
Animal animal = (Animal)Enum.Parse(typeof(Animal), str, true); // case insensitive
xxxxxxxxxx
var foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
if (Enum.IsDefined(typeof(YourEnum), foo))
{
return foo;
}
xxxxxxxxxx
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;
}
xxxxxxxxxx
/// 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);
}
xxxxxxxxxx
string stringValue = "SomeValue"; // The string value you want to convert
YourEnum enumValue;
if (Enum.TryParse(stringValue, out enumValue))
{
// The conversion was successful
// 'enumValue' now represents the corresponding enum value
Console.WriteLine("Converted value: " + enumValue);
}
else
{
// The string value does not match any of the enum values
Console.WriteLine("Invalid string value");
}