Associating Strings with enums and conversions

Converts from enum to string, from enum type to a list of enums, and from string to enum in C#

1st step: Add the description for each enum value:

using System.ComponentModel;

public enum LanguageEnum
{
	[Description("English")]
	English = 1,
	[Description("Esperanto")]
	Esperanto = 2,
	[Description("French")]
	French= 3,
	[Description("Portuguese")]
	Portuguese = 4,
	[Description("Spanish")]
	Spanish = 5
}

Here are the conversion methods (returns ArgumentException if not found / type is invalid):

using System.Reflection;
using System.ComponentModel;

/// <summary>
/// Converts any string to the specified enum type
/// </summary>
public static object ToEnum(string StringValue, Type EnumType)
{
	if (EnumType == null)
		throw new Exception("StringToEnum(): EnumType is null");

	if (StringValue == null)
		throw new Exception("StringToEnum(): StringValue is null");

	string[] names = Enum.GetNames(EnumType);
	foreach (string name in names)
	{
		if (ToString((Enum)Enum.Parse(EnumType, name)).Equals(StringValue))
			return Enum.Parse(EnumType, name);
	}

	throw new ArgumentException("StringValue is not specified by EnumType.");
}

/// <summary>
/// Converts any enum to string
/// </summary>
public static string ToString(Enum EnumValue)
{
	if (EnumValue == null)
		throw new Exception("StringToEnum(): EnumValue is null");

	FieldInfo fi = EnumValue.GetType().GetField(EnumValue.ToString());

	DescriptionAttribute[] attributes =
		(DescriptionAttribute[])
		fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

	if (attributes.Length > 0)
		return attributes[0].Description;
	else
		return EnumValue.ToString();
}

/// <summary>
/// Converts any enum type to a list of enums
/// </summary>
public static IList<T> ToList<T>()
{
	Type enumType = typeof(T);

	if (enumType.BaseType != typeof(Enum))
		throw new ArgumentException("T must be of type System.Enum");

	Array aEnumValues = Enum.GetValues(enumType);
	List<T> list = new List<T>(aEnumValues.Length);

	foreach (int val in aEnumValues)
		list.Add((T)Enum.Parse(enumType, val.ToString()));

	return list;
}

 

Advertisements

One thought on “Associating Strings with enums and conversions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s