Click here to Skip to main content
15,860,972 members
Articles / Programming Languages / C#

Enum With Text Value in C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (10 votes)
7 Jun 2014CPOL1 min read 41.4K   154   14   12
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.

C++
[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.

C++
/*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.

C++
[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.

C++
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)


Written By
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Question[My vote of 1] Good effort but... Pin
Suvabrata Roy8-Jun-14 21:55
professionalSuvabrata Roy8-Jun-14 21:55 
AnswerRe: [My vote of 1] Good effort but... Pin
DiponRoy9-Jun-14 7:12
mvaDiponRoy9-Jun-14 7:12 
GeneralRe: [My vote of 1] Good effort but... Pin
Suvabrata Roy9-Jun-14 18:26
professionalSuvabrata Roy9-Jun-14 18:26 
GeneralRe: [My vote of 1] Good effort but... Pin
DiponRoy10-Jun-14 1:45
mvaDiponRoy10-Jun-14 1:45 
GeneralRe: [My vote of 1] Good effort but... Pin
Suvabrata Roy10-Jun-14 2:20
professionalSuvabrata Roy10-Jun-14 2:20 
So you are trying to relate some database flag with string.

Here is a nice example how to Use Enum in EF : http://msdn.microsoft.com/en-in/data/hh859576.aspx[^]
Another : http://msdn.microsoft.com/en-in/data/jj248772[^]

I would suggest you to not to do the same because it will consume more process then required for the same.
You can use some utility class where you will pass the same Enum and get back the desire string value you required.
Life is all about share and care...

public class Life : ICareable,IShareable
{
// implements yours...
}

GeneralRe: [My vote of 1] Good effort but... Pin
DiponRoy19-Apr-15 11:37
mvaDiponRoy19-Apr-15 11:37 
GeneralDescriptionAttribute Pin
PIEBALDconsult8-Jun-14 4:47
mvePIEBALDconsult8-Jun-14 4:47 
SuggestionWhy not DisplayName Pin
Dusan Paulovic7-Jun-14 19:37
Dusan Paulovic7-Jun-14 19:37 
GeneralRe: Why not DisplayName Pin
F. Xaver10-Jun-14 0:15
F. Xaver10-Jun-14 0:15 
GeneralRe: Why not DisplayName Pin
Dusan Paulovic10-Jun-14 4:50
Dusan Paulovic10-Jun-14 4:50 
GeneralMy vote of 1 Pin
Dusan Paulovic7-Jun-14 19:35
Dusan Paulovic7-Jun-14 19:35 
GeneralRe: My vote of 1 Pin
DiponRoy19-Apr-15 11:28
mvaDiponRoy19-Apr-15 11:28 

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

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