I have an enumeration:
public enum MyColours
{
Red,
Green,
Blue,
Yellow,
Fuchsia,
Aqua,
Orange
}
and I have a s
All you need is Enum.Parse.
One thing that might be useful to you (besides the already valid/good answers provided so far) is the StringEnum idea provided here
With this you can define your enumerations as classes (the examples are in vb.net):
< StringEnumRegisteredOnly(), DebuggerStepThrough(), ImmutableObject(True)> Public NotInheritable Class eAuthenticationMethod Inherits StringEnumBase(Of eAuthenticationMethod)
Private Sub New(ByVal StrValue As String) MyBase.New(StrValue) End Sub < Description("Use User Password Authentication")> Public Shared ReadOnly UsernamePassword As New eAuthenticationMethod("UP") < Description("Use Windows Authentication")> Public Shared ReadOnly WindowsAuthentication As New eAuthenticationMethod("W")
End Class
And now you could use the this class as you would use an enum: eAuthenticationMethod.WindowsAuthentication and this would be essentially like assigning the 'W' the logical value of WindowsAuthentication (inside the enum) and if you were to view this value from a properties window (or something else that uses the System.ComponentModel.Description property) you would get "Use Windows Authentication".
I've been using this for a long time now and it makes the code more clear in intent.
(MyColours)Enum.Parse(typeof(MyColours), "red", true); // MyColours.Red
(int)((MyColours)Enum.Parse(typeof(MyColours), "red", true)); // 0
You might also want to check out some of the suggestions in this blog post: My new little friend, Enum<T>
The post describes a way to create a very simple generic helper class which enables you to avoid the ugly casting syntax inherent with Enum.Parse
- instead you end up writing something like this in your code:
MyColours colour = Enum<MyColours>.Parse(stringValue);
Or check out some of the comments in the same post which talk about using an extension method to achieve similar.
var color = Enum.Parse<Colors>("Green");
You can cast the int to an enum
(MyColour)2
There is also the option of Enum.Parse
(MyColour)Enum.Parse(typeof(MyColour), "Red")