Sure, here are two ways to get an enum value from a string value in C#:
Using the Enum.Parse() method:
C#
enum MyEnum {
Value1,
Value2,
Value3
}
string myString = "Value1";
// Get the enum value from the string 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 TryParse() method:
C#
enum MyEnum {
Value1,
Value2,
Value3
}
string myString = "Value1";
// Get the enum value from the string using the TryParse() method.
bool success = Enum.TryParse(myString, out MyEnum myEnum);
// Check if the conversion was successful.
if (success) {
// The conversion was successful.
} else {
// The conversion was not successful.
}
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.TryParse(myString, out MyEnum myEnum) method tries to cast the
myString variable to an enum. If the conversion is successful, then the
success variable is set to true and the myEnum variable is set to the enum value. Otherwise, the
success variable is set to false and the myEnum variable is not modified.
Which method you use depends on your specific needs. If you need to get the enum value 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
TryParse() method is a good option.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here are two ways to get an enum value from a string value 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.TryParse()method:C#
In this example, the
myStringvariable is a string that has the value of"Value1". TheMyEnumenum has three values:Value1,Value2, andValue3. TheEnum.TryParse(myString, out MyEnum myEnum)method tries to cast themyStringvariable to an enum. If the conversion is successful, then thesuccessvariable is set totrueand themyEnumvariable is set to the enum value. Otherwise, thesuccessvariable is set tofalseand themyEnumvariable is not modified.Which method you use depends on your specific needs. If you need to get the enum value 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 theTryParse()method is a good option.