C# – Enum of string

When I am building a class for associating my program for a specific file extension, I remembered to an old solution for building an enumeration with type of string. To declare an enumeration in C#, we use code below

enum NameOfEnumeration

The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. So enum supports only byte, sbyte, short, ushort, int, uint, long, or ulong. What would we do if we want to have an enumeration with string? The following example code below will illustrate how an enumeration of string can be built. However it doesn’t work exactly as we expect , for example, it won’t return a string we cast its value but we need to call a method from a helper class to get it’s string. The string of enum value will be stored through DescriptionAttribute which specifies a description for a property or event. Then when we want to get string, we just access this description and fetch value back. For example, we have a Bookstore enum

enum BookStore

You can see that there is an url string for each enum value. We would like to use these string values in our code, but we can not use them as enum value. So declare these strings in description attribute and get them later through these two static functions

class EnumString
	public static string GetString(Enum enValue)
		FieldInfo fiInfo = enValue.GetType().GetField(enValue.ToString());
		DescriptionAttribute[] daArray = fiInfo.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
		return daArray.Length > 0 ? daArray[0].Description : "";

	public static object GetValue(string strDescription, Type tyEnum)
		string[] arrNames = Enum.GetNames(tyEnum);
		foreach (string strTemp in arrNames)
			if (GetString(Enum.Parse(tyEnum,strTemp) as Enum).Equals(strDescription)) return Enum.Parse(tyEnum,strTemp);
		throw new Exception("No value found for this description");

The GetString function receives an enum value as its argument and gives string value back. On the contrary, the GetValue function receives a string value and enum type to specify to which enum value the string belongs to.

 static void Main(string[] args)
	Console.WriteLine(EnumString.GetValue("www.amazon.com", typeof(BookStore)).ToString());

Leave a comment

Your email address will not be published. Required fields are marked *