ExtensionMethod.NET Home of 819 C#, Visual Basic, F# and Javascript extension methods

GetEnumDescription

Gets the description attribute assigned to an item in an Enum.

Source

public static class EnumExtensions
{
	public static string GetEnumDescription(this Enum value)
	{
		System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString());

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

		if (attributes != null && attributes.Length > 0)
			return attributes[0].Description;
		else
			return value.ToString();
	}
}

Example

enum ErrorCode
{
	[Description("Failed to print")]
	FailedToPrint = 345,

	[Description("Failed to save")]
	FailedToSave = 233,
}

...
...

string res = ErrorCode.FailedToPrint.GetEnumDescription(); // Failed to print

Author: Jarod Weiss

Submitted on: 7 nov 2019

Language: csharp

Type: System.Enum

Views: 3735