how to use enum description in c#
Microsoft Net Framework

Here i'm going to explain how you can create enum and get the Description  of your enum 

for instance 

your enum class

 public enum MyEnum
    {
        [Description("Invalid Email or Passwrod")]
        INVALID_LOGIN = 2002

  }

Now you want to get [Description("Invalid Email or Passwrod")] against INVALID_LOGIN ,so how you can achieve this its simple just follow the step

1-create a Static class ,in my case my static class name is 

public static class BusinessManager and the my static method name with implimentation is below

public static string GetEnumDescription<T>(this T e) where T : IConvertible
        {
            string description = null;

            if (e is MyEnum)
            {
                Type type = e.GetType();
                Array values = System.Enum.GetValues(type);

                foreach (int val in values)
                {
                    if (val == e.ToInt32(CultureInfo.InvariantCulture))
                    {
                        var memInfo = type.GetMember(type.GetEnumName(val));
                        var descriptionAttributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                        if (descriptionAttributes.Length > 0)
                        {
                            description = ((DescriptionAttribute)descriptionAttributes[0]).Description;
                        }

                        break;
                    }
                }
            }

            return description;
        }

2- so how can i call this in my desired code just follow as the below

MyEnum myEnum= MyEnum.INVALID_LOGIN ​;

  string dec = myEnum.GetEnumDescription();

 

Share This with your friend by choosing any social account


Upcoming Articles
You may also read following recent Post
Copyright Future Minutes © 2015- 2024 All Rights Reserved.   Terms of Service  |   Privacy Policy |  Contact US|  Pages|  Whats new?
Update on: Dec 20 2023 05:10 PM
03
07

New Messages

George Floyd
  • Edit Post Edit This Post within a Hour
  • Hide Chat Hide This Post
  • Delete Chat If inappropriate Post By Mistake
  • Report Inappropriate Chat
  • 4.5kb
  • Hi James! Please remember to buy the food for tomorrow! I’m gonna be handling the gifts and Jake’s gonna get the drinks
  • Hi James! Please remember to buy the food for tomorrow! I’m gonna be handling the gifts and Jake’s gonna get the drinks
  • Hi James! Please remember to buy the food for tomorrow! I’m gonna be handling the gifts and Jake’s gonna get the drinks