Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Enum With Text Value in C#

0.00/5 (No votes)
7 Jun 2014 1  
Enum with text value in C#

Introduction

In C#, we use enums frequently. Enum can only inherit from types byte, sbyte, short, ushort, int, uint, long, or ulong. But sometimes, we also may want to assign text value with it to extend its uses.

Background

I have been working with Entity framework code first. And I had been using enums to hold information like:

  • UserType (SuperUser, AdminUser, … etc.)
  • Permission (UserManage, UnitManage, … etc.) and few more

It was going quite well. But a problem was introduced when I went to show the information based on enum values to the real user.

Real user doesn’t know what emun is. User type values like (0, 1, 2… etc.) or (SuperUser, AdminUser, … etc.) are confusing to them. Words like (Super User, Admin User, … etc.) seem quite suitable to them.

So I started to add some extra code using attributes and extinction methods, so that my emun could hold some little text description regarding it.

Using the Code

Here is the enum which will hold our text values. Here, we are using two custom attributes CustomEnum and TextValue which we are going to see in detail within moments.

[CustomEnum(true)]                           /*Important to use CustomEnum(true)*/
public enum PermissionEnum
{
    [TextValue("User setup manage")]        /*Holds the text value*/
    UserManage = 10,
    [TextValue("Unit setup manage")]
    UnitManage = 2,
    [TextValue("Exam setup manage")]
    ExamManage = 3,
    ExaminerManage = 1                     /*Its not necessary to use TextValue on all*/
}

Once we have created the enum, we will use it like this. Here, TextValue() is an extension method to get the assigned text.

/*Use of the custom enum*/
const PermissionEnum aPermission = PermissionEnum.UserManage;
String name = aPermission.ToString();                       //Shows the normal string value
String textValue = aPermission.TextValue();                 //Shows the assigned text value 
int value = (int)aPermission;                               //Shows the Value

Here are the two custom attributes, CustomEnum and TextValue that we mentioned earlier.

[AttributeUsage(AttributeTargets.Enum)]
public class CustomEnumAttribute : Attribute
{
    public bool IsCustomEnum { get; set; }
    public CustomEnumAttribute(bool isCustomEnum) : this()
    {
       IsCustomEnum = isCustomEnum;
    }

    private CustomEnumAttribute()
    {
       IsCustomEnum = false;
    }
}
[AttributeUsage(AttributeTargets.Field)]
class TextValueAttribute : CustomEnumAttribute
{
    public String Value { get; set; }
    public TextValueAttribute(string textValue) : this()
    {
        if (textValue == null)
        {
            throw new NullReferenceException("Null not allowed in textValue at TextValue attribute");
        }
        Value = textValue;
    }

    private TextValueAttribute() : base(true)
    {
        Value = string.Empty;
    }
}

And last of all, we need the extension method for the enum which will help us to get the assigned text.

public static class CustomEnumUtility
{
    /// To use this extantion method, the enum need to have CustomEnumAttribute with CustomEnumAttribute(true)
    public static string TextValue(this Enum myEnum)
    {
        string value = string.Empty;
        /*Check : if the myEnum is a custom enum*/
        var customEnumAttribute = (CustomEnumAttribute) myEnum
                                  .GetType()
                                  .GetCustomAttributes(typeof(CustomEnumAttribute), false)
                                  .FirstOrDefault();

        if (customEnumAttribute == null)
        {
            throw new Exception("The enum don't contain CustomEnumAttribute");
        }
        else if (customEnumAttribute.IsCustomEnum == false)
        {
            throw new Exception("The enum is not a custom enum");
        }

        /*Get the TextValueAttribute*/
        var textValueAttribute = (TextValueAttribute)myEnum
                                     .GetType().GetMember(myEnum.ToString()).Single()
                                     .GetCustomAttributes(typeof(TextValueAttribute), false)
                                     .FirstOrDefault();
        value = (textValueAttribute != null) ? textValueAttribute.Value : string.Empty;
        return value;
    }
}

You may find the project in the attachment.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here