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, the code can be consumed like this:

string enumDesc = MyEnum.HereIsAnother.DescriptionAttr();
string classDesc = myInstance.SomeProperty.DescriptionAttr();

Comments

  1. 2019 ford edge titanium for sale
    Looking for 2019 ford titanium mokume gane edge titanium? We have some titanium welding of titanium vs platinum the ford escape titanium best prices for you. The most accurate and reliable source of accurate & citizen super titanium armor unbiased

    ReplyDelete

Post a Comment

Popular posts from this blog

Private Chat Using Node js and socket.io with encrypt and decrypt message and insert into mongo db

How To Migrate MVC 3 Application To MVC 5

Populate a drop-down in Vue.js and Asp.net Core from an ajax call