Tuesday, July 03, 2007

C# - How to check if a property type is an Enum

class EnumTests
public static void Run()
// convert a string into a color Enum
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 = "OrangeGreen";

if (Enum.IsDefined(typeof(Colour), nonColour))
c = (Colour)Enum.Parse(typeof(Colour), nonColour, true);
Console.WriteLine("'{0}' is an undefined Color", nonColour);

//Check if c is an Enum
Console.WriteLine("c is an Enum = {0} ", c.GetType().IsEnum);

#region Helper Classes

enum Colour