Obtaining the string value of an enumeration name

| | Comments (0)

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.

Leave a comment

About this Entry

This page contains a single entry by Rob published on March 23, 2007 9:00 AM.

Link Dump was the previous entry in this blog.

Converting Request.InputStream to a string - Part 1 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 5.02