I am Utpal Vishwas from Uttar Pradesh. Have completed my B. Tech. course from MNNIT campus Prayagraj in 2022. I have good knowledge of computer networking.
Sure, here are two ways to convert a string to an enum in C#:
Using the Enum.Parse() method:
C#
enum MyEnum {
Value1,
Value2,
Value3
}
string myString = "Value1";
// Convert the string to an enum using the Enum.Parse() method.
MyEnum myEnum = Enum.Parse(typeof(MyEnum), myString);
In this example, the myString variable is a string that has the value of
"Value1". The MyEnum enum has three values: Value1,
Value2, and Value3. The Enum.Parse(typeof(MyEnum), myString) method casts the
myString variable to an enum.
Using the try-catch block:
C#
enum MyEnum {
Value1,
Value2,
Value3
}
string myString = "Value1";
// Convert the string to an enum using the try-catch block.
try {
myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), myString);
} catch (Exception e) {
// The string is not a valid enum value.
}
In this example, the myString variable is a string that has the value of
"Value1". The MyEnum enum has three values: Value1,
Value2, and Value3. The try-catch block first tries to cast the
myString variable to an enum. If the myString variable is not a valid enum value, then the
Exception 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 the
try-catch block is a good option.
Liked By
Write Answer
Convert a string to an enum in C#
Join MindStick Community
You have need login or register for voting of answers or question.
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.