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
RT @CodeSnippetsNET: Get Enum by Descritption Attribute C# and http://t.co/8NYPvKyVOV http://t.co/GzLjORwhLP #csharp #dotnet #vb