Posts

Showing posts with the label Enum

Get C# Enum Description from Name And Value

enum with Description attributes like this: public enum MyEnum { Transaction = 1 , [ Description ( "Transaction Detail" )] TransactionDetail = 2 , [ Description ( "Transaction Reference Number" )] TransactionRefno = 3 } I put the code together from the accepted answer in a generic extension method, so it could be used for all kinds of objects: public static string DescriptionAttr < T >( this T source ) { FieldInfo fi = source . GetType (). GetField ( source . ToString ()); DescriptionAttribute [] attributes = ( DescriptionAttribute []) fi . GetCustomAttributes ( typeof ( DescriptionAttribute ), false ); if ( attributes != null && attributes . Length > 0 ) return attributes [ 0 ]. Description ; else return source . ToString (); } Using an enum like in the original post, or any other class whose property is decorated with the Description attribute,