Possible Duplicate:
How do I Convert a string to an enum in C#?
How to Convert (to Cast) a string ( a text) to be Enum tag value in C#
Possible Duplicate:
How do I Convert a string to an enum in C#?
How to Convert (to Cast) a string ( a text) to be Enum tag value in C#
You can do this:
MyEnum oMyEnum = (MyEnum) Enum.Parse(typeof(MyEnum), "stringValue");
While all the Enum.Parse people are correct, there's now Enum.TryParse!
Which improves things greatly.
I usually use generic Enum class for this stuff:
public static class Enum<T>
{
public static T Parse(string value)
{
return (T)Enum.Parse(typeof(T), value);
}
public static List<T> GetValues()
{
List<T> values = new List<T>();
foreach (T value in Enum.GetValues(typeof(T)))
values.Add(value);
return values;
}
public static string GetName(object value)
{
return Enum.GetName(typeof(T), value);
}
// etc
// you also can add here TryParse
}
Usage is more simple:
Enum<DayOfWeek>.Parse("Friday");
Or wrap it in a method like this:
T ParseEnum<T>(string stringValue)
{
return (T) Enum.Parse(typeof(T), stringValue);
}
.net provides some static methods on the System.Enum type to do this, and aside from the code that actually does the cast, there are several things to consider:
So if you have an enum:
public enum TestEnum
{
FirstValue,
SecondValue
}
Then the following 2 static methods are provided by the System.Enum class to cast a string value to an enum type:
Enum.IsDefined (.net 1.1 - 4 + silverlight) (usage)
TestEnum testEnum;
if( Enum.IsDefined(typeof(TestEnum), "FirstValue") )
{
testEnum = (TestEnum)Enum.Parse(typeof(TestEnum), "FirstValue");
}
Enum.TryParse ( .net 4 + silverlight) (usage)
TestEnum testEnum;
bool success = Enum.TryParse("FirstValue", out testEnum);
Alternatively, the Enum.Parse method (as mentioned by others) is provided if you do not need to perform any safety-checking. However, if you attempt to do something like this in our example,
Enum.Parse(TestEnum, "ThisValueDoesNotExist")
then .net will throw a System.ArgumentException which you have to handle.
So in short, while the syntax to do what you ask is simple, there are a few precautions I would recommend considering to ensure error-free code, especially if you are parsing strings obtained from user input. If the string is from a settings file or some other sort of value you can be sure is defined in your enum type, then it may be ok to skip some of the extra steps I have outlined in my answer.
I hope this helps!