Convert a string into an enum

CodeKeep C# Feed Aprile 30th, 2008

Description: Source: http://blogs.msdn.com/tims/archive/2004/04/02/106310.aspx

Link: http://www.codekeep.net/snippets/c76f9433-c53c-4cae-bf5e-e309b1f51207.aspx

enum Colour
{
  Red,
  Green,
  Blue
} 

// ...
Colour c = (Colour) Enum.Parse(typeof(Colour), "Red", true);
Console.WriteLine("Colour Value: {0}", c.ToString());

// Picking an invalid colour throws an ArgumentException. To
// avoid this, call Enum.IsDefined() first, as follows:
string nonColour = "Polkadot";

if (Enum.IsDefined(typeof(Colour), nonColour))
  c = (Colour) Enum.Parse(typeof(Colour), nonColour, true);
else
  MessageBox.Show("Uh oh!");

  • .NET
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Comments are closed.

Trackback URI |