Convert an Enum to String

Posted by Aamir Hasan on ASP.net Weblogs See other posts from ASP.net Weblogs or by Aamir Hasan
Published on Wed, 31 Mar 2010 18:04:00 GMT Indexed on 2010/03/31 18:13 UTC
Read the original article Hit count: 546

Filed under:

 

Retrieves the name of the constant in the specified enumeration that has the specified value.

If you have used an enum before you will know that it can represent numbers (usually int but also byte, sbyte, short, ushort, int, uint, long, and ulong) but not strings.

I created my enum and I was in the process of coding up a lookup table to convert my enum parameter back into a string when I found this handy method called Enum.GetName().


using System;

public class GetNameTest {
enum Colors { Red, Green, Blue, Yellow };
enum Styles { Plaid, Striped, Tartan, Corduroy };

public static void Main() {

Response.Write("The 4th value of the Colors Enum is" + Enum.GetName(typeof(Colors), 3));
Response.Write("The 4th value of the Styles Enum is "+ Enum.GetName(typeof(Styles), 3));
}
}

Reference:http://msdn.microsoft.com/en-us/library/system.enum.getname.aspx
http://www.studentacad.com/post/2010/03/31/Convert-an-Enum-to-String.aspx 

© ASP.net Weblogs or respective owner

Related posts about ASP.NET