How to get Enum by Descritption Attribute in C# and VB.NET

To get Enum by Descritption Attribute in C# and VB.NET you can use the following snippet.

Sample C#

public static T GetEnumFromDescriptionAttribute<T>(string description)
{
	var type = typeof(T);
	if (!type.IsEnum) throw new InvalidOperationException();
	foreach (var fieldInfo in type.GetFields())
	{
		var descriptionAttribute = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) as DescriptionAttribute;
		if (descriptionAttribute != null)
		{
			if (descriptionAttribute.Description != description) continue;
			return (T)fieldInfo.GetValue(null);
		}
		if (fieldInfo.Name != description) continue;
		return (T)fieldInfo.GetValue(null);
	}
	return default(T);
}

Sample VB.NET

Public Shared Function GetEnumFromDescriptionAttribute(Of T)(description As String) As T
	Dim type = GetType(T)
	If Not type.IsEnum Then
		Throw New InvalidOperationException()
	End If
	For Each fieldInfo As var In type.GetFields()
		Dim descriptionAttribute = TryCast(Attribute.GetCustomAttribute(fieldInfo, GetType(DescriptionAttribute)), DescriptionAttribute)
		If descriptionAttribute IsNot Nothing Then
			If descriptionAttribute.Description <> description Then
				Continue For
			End If
			Return DirectCast(fieldInfo.GetValue(Nothing), T)
		End If
		If fieldInfo.Name <> description Then
			Continue For
		End If
		Return DirectCast(fieldInfo.GetValue(Nothing), T)
	Next
	Return Nothing
End Function

Please Share us:
Please rate this snippet

One thought on “How to get Enum by Descritption Attribute in C# and VB.NET

Leave a Reply