Convert a string to an enum in C#
Convert a string to an enum in C#
512
21-Aug-2023
Aryan Kumar
23-Aug-2023Sure, here are two ways to convert a string to an enum in C#:
Enum.Parse()method:C#
In this example, the
myStringvariable is a string that has the value of"Value1". TheMyEnumenum has three values:Value1,Value2, andValue3. TheEnum.Parse(typeof(MyEnum), myString)method casts themyStringvariable to an enum.try-catchblock:C#
In this example, the
myStringvariable is a string that has the value of"Value1". TheMyEnumenum has three values:Value1,Value2, andValue3. Thetry-catchblock first tries to cast themyStringvariable to an enum. If themyStringvariable is not a valid enum value, then theExceptionexception is caught.Which method you use depends on your specific needs. If you need to cast a string to an enum and you don't need to do any further processing on the enum value, then the
Enum.Parse()method is a good option. If you need to do further processing on the enum value, then thetry-catchblock is a good option.