Home
Manage Your Code
Snippet: Convert a string into an enum (C#)
Title: Convert a string into an enum Language: C#
Description: Source: http://blogs.msdn.com/tims/archive/2004/04/02/106310.aspx Views: 181
Author: Filip K Date Added: 4/30/2008
Copy Code  
1enum Colour
2{
3  Red,
4  Green,
5  Blue
6} 
7
8// ...

9Colour c = (Colour) Enum.Parse(typeof(Colour), "Red", true);
10Console.WriteLine("Colour Value: {0}", c.ToString());
11
12// Picking an invalid colour throws an ArgumentException. To

13// avoid this, call Enum.IsDefined() first, as follows:

14string nonColour = "Polkadot";
15
16if (Enum.IsDefined(typeof(Colour), nonColour))
17  c = (Colour) Enum.Parse(typeof(Colour), nonColour, true);
18else
19  MessageBox.Show("Uh oh!");