Get description associated with enumeration item in C#

In previous articles Get enumeration items as a list in C# and Populate dropdown with enumeration items in ASP.NET Core we that saw how to get enumeration items as a collection to bind it to data controls like dropdown etc.
In this article we will see that how can we get the description given as an attribute with an item. We may need this information on various places, say we have listing of users and we need to show each user’s status but in a descriptive way.

Here is our example enumeration:

  enum UserStatus
    {
        [Description("Pending Verification")]
        PendingVerification = 1,
        [Description("Pending Admin Approval")]
        PendingAdminApproval = 2,
        [Description("Active")]
        Active = 3,
        [Description("Blocked by Admin")]
        BlockedByAdmin = 4
    }

To accomplish this we need to create an extension method as shown below:

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

            if (e is Enum)
            {
                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)
                        {
                            // we're only getting the first description we find
                            // others will be ignored
                            description = ((DescriptionAttribute)descriptionAttributes[0]).Description;
                        }

                        break;
                    }
                }
            }

            return description;
        }       
       
    }

After defining the above class and method then we can get the description of an enumeration item as given below:

 var userStatus = UserStatus.PendingAdminApproval;
     Label1.Text = userStatus.GetEnumDescription();

and here is the output:


Comments
Share it