Obtaining the string value of an enumeration name

A useful trick I've picked up recently is the ability to get the name of a value of an enumeration in C#. Using the following example enumeration:

enum fruit
{
apples,
pears,
oranges
}

The following sample code can be used to pop-up a message box stating what the name of the enumeration value passed in is:

function void WhatIsTheFruitCalled (fruit fruitValue)
{
string sFruitName = Enum.GetName(typeof(fruit), fruitValue);
MessageBox.Show(sFruitName);
}

The code could be made generic and more robust by changing it to the following:

function string WhatIsTheFruitCalled2 (fruit fruitValue)
{
string sFruitName = "";
if (Enum.IsDefined(typeof(fruit), fruitValue))
{
sFruitName = Enum.GetName(typeof(fruit), fruitValue);
}
return sFruitName;
}

Of course this code is specific to an enum of fruit, but it's a fairly simple exercise to make this generic as below:

public static string GetEnumValueName(T Value)
{
if (Value.GetType().IsEnum)
{
Type t = Value.GetType();
if (Enum.IsDefined(t, Value))
{
return Enum.GetName(t, Value);
}
else
{
throw new ArgumentException(string.Format("Value out of range for enumeration of type {0}", t.Name), "Value");
}
}
else
{
throw new ArgumentException("Value must be an Enumeration", "Value");
}
}

The option's there to suppress the exceptions and return empty string instead if that's the desired result, but this is a tidy bit of logic.

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment