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

Extending Enum to return attached string

By , 25 Oct 2012
 

No of time there is requirement of getting string of Enum value to display purpose or to perform other task. So to deal with this requirement I wrote one extension function that get the string attached with the enum value.

Note : here attached string value is the attribute that is attached with each enum value that you are creating in enum variable.

Following is extension function to get string attached with enum.

public static class MyExtensions
{
   public static string GetEnumDescription(this Enum value)
   {            
         FieldInfo fi = value.GetType().GetField(value.ToString());
 
         object[] attributes = fi.GetCustomAttributes(true);
 
         if (attributes != null &&
            attributes.Length > 0)
                return ((DescriptionAttribute) attributes[0]).Description;
         else
                return value.ToString();
    }
}

The code above is making use of the reflection feature of .net framework. With the help of reflection it first get the information about the field and than get the attribute attached with that field. Attribute attached with enum value is DescriptionAttribute so code convert attribute object to DescriptionAttribute and return string attached with it. If there is no attribute attached with enum value it returns the interger value of enum as string.
 

Note : Attribute is metadata attached with the type you can attache metadata with class, function , property etc. Read More: Attributes (C# Programming Guide)
 

Following is simple program that is making use of extension function and to display the string attached with the enum value.

class Program
    {
        public enum WeekDay
        {
            [Description("Monday")]
            Monday,
            [Description("Tuesday")]
            Tuesday
        }
 
        static void Main(string[] args)
        {
            string str = (WeekDay.Monday).GetEnumDescription();
            Console.WriteLine(str);
            Console.ReadLine();
        }
    }

In above code there is enum create with the name WeekDay and as per the requirement it require to attache attribute with the each enum value to function to work properly if no attribute attached with enum value than function return value of enum i.e interger value associated with the enum.
 

So when code in "Main function" get executed call to function "GetEnumDescription" it return "Monday" as output on the console window which is associated with enum value.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Pranay Rana
Software Developer (Senior) GMind Solusion
India India
Member

Microsoft C# MVP

 
Hey, I am Pranay Rana, working as a ITA in MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.
 
For me def. of programming is : Programming is something that you do once and that get used by multiple for many years
 

You can visit my blog

StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr
 
Awards:



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 2memberKlaus Luedenscheidt26 Oct '12 - 17:31 
You should take a look first, if similar tips where posted here before. See Vijay's link samples
GeneralMy vote of 3memberJohn Brett25 Oct '12 - 23:22 
Your extension method requests all of the custom attributes from the field, then makes the assumption that the first one it finds will be of type DescriptionAttribute. Needless to say, this will fail if your enum uses any other attributes.
 
It also doesn't address the question of internationalization. A common origin of this requirement is to be able to display a human-readable form of the enum - and that ought to be in the reader's own language.
 
So not the best implementation of this on CodeProject.
QuestionAnd a few more tips / articles like this on CP :)memberVijay Gill25 Oct '12 - 22:30 
I found these by using the search facility in this site. Reporting only first few....
 
TIP: Descriptions for enum values[^]
 
Mapping Text to Enum entries[^]
 
TIP: Descriptions for enum values[^]
 
Enum Display Extension[^]
 
Human readable strings for enum elements[^]

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 26 Oct 2012
Article Copyright 2012 by Pranay Rana
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid