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);
else
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
{
Red,
Green,
Blue
}

#endregion

3 comments:

hemant said...

Good Anser

lee woo said...

Progress is impossible without change, and those who cannot change their minds cannot change anything. See the link below for more info.


#minds
www.ufgop.org

Zepharia Andres said...

I really enjoyed reading your article. I found this as an informative and interesting post, so i think it is very useful and knowledgeable. I would like to thank you for the effort you have made in writing this article.


edupdf.org