Convert a string to an enum in C#
Convert a string to an enum in C#
126
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
myString
variable is a string that has the value of"Value1"
. TheMyEnum
enum has three values:Value1
,Value2
, andValue3
. TheEnum.Parse(typeof(MyEnum), myString)
method casts themyString
variable to an enum.try-catch
block:C#
In this example, the
myString
variable is a string that has the value of"Value1"
. TheMyEnum
enum has three values:Value1
,Value2
, andValue3
. Thetry-catch
block first tries to cast themyString
variable to an enum. If themyString
variable is not a valid enum value, then theException
exception 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-catch
block is a good option.