Click here to Skip to main content
Click here to Skip to main content

Tagged as

Enum With Text Value in C#

, 7 Jun 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

DiponRoy

Bangladesh Bangladesh
No Biography provided

Comments and Discussions

 
Question[My vote of 1] Good effort but... PinprofessionalSuvabrata Roy8-Jun-14 22:55 
AnswerRe: [My vote of 1] Good effort but... Pinmemberdiponsust9-Jun-14 8:12 
GeneralRe: [My vote of 1] Good effort but... PinprofessionalSuvabrata Roy9-Jun-14 19:26 
GeneralRe: [My vote of 1] Good effort but... Pinmemberdiponsust10-Jun-14 2:45 
GeneralRe: [My vote of 1] Good effort but... PinprofessionalSuvabrata Roy10-Jun-14 3:20 
GeneralDescriptionAttribute PinmemberPIEBALDconsult8-Jun-14 5:47 
SuggestionWhy not DisplayName PinmemberDusan Paulovic7-Jun-14 20:37 
GeneralRe: Why not DisplayName PinmemberF. Xaver10-Jun-14 1:15 
GeneralRe: Why not DisplayName PinmemberDusan Paulovic10-Jun-14 5:50 
GeneralMy vote of 1 PinmemberDusan Paulovic7-Jun-14 20:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.1411023.1 | Last Updated 8 Jun 2014
Article Copyright 2014 by DiponRoy
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid