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")]
     
 ...  read more

Sometime we need to get enumeration items as a list to bind it to some data controls like drop downs.

Here is how we can do that. Suppose we have following enumeration:

 enum UserStatus
    {
        PendingVerification = 1,
        PendingAdminApproval = 2,
        Active = 3,
        BlockedByAdmin = 4
    }

We want to bind a dropdown on manage users page with these items. As you know dropdown have two properties for each item, one to handle display value and the other to handle backend value.

Using the current definition of enumeration we can use the name of enumeration item as display property and underlying integer value as backend value but it will not look good as there will be no space between words like PendingVerification. It will be more readable if it is Pending Verification.

So let’s add Description attribute to the enumeration items. Updated enumeration will look like this:

    enum UserStatus
    {
        [Description("Pending Verification")]
        PendingVerification
 ...  read more