by
192 12
0
6
15k
105
Top 1% !
Popular
Famous
Pearl of Wisdom
Tagged
Specified
Popularity: 221st place
Created
Modified May 8, 2013
This snippet is Public
.NETFramework3.5
InputName0description
InputType0string
LanguageCSharp
LicenseMIT_X11
MethodNameGetValueFromDescription
OutputTypeT

C#: Get Enum from Description attribute

This is a generic extension method which gets the Description attribute from an Enum
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/1067/C---Get-Enum-from-Description-attribute?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
public static T GetValueFromDescription<T>(string description) { var type = typeof(T); if (!type.IsEnum) throw new InvalidOperationException(); foreach (var field in type.GetFields()) { var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if (attribute != null) { if (attribute.Description == description) return (T)field.GetValue(null); } else { if (field.Name == description) return (T)field.GetValue(null); } } throw new ArgumentException("Not found.", "description"); // or return default(T); }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus