Friday 8 April 2011

C#: DescriptionAttribute with Enums


If you've ever created an Enum, usually the entities you define within the enum are not user friendly. I.e. outputting to the console "EnumDescEntityTwo". We would probably prefer it to have whitespaces "Enum Desc Entity Two" or even be called something totally different "Cheese Sandwich".

So there are a few ways to achieve this without writing a bunch of conditions in the GUI layer.


1. Map the Enums to database table.

I.e.
- ID (For DB use only)
- EnumID (Maps onto the Enum value)
- EnumDescription (A description representing the enum)

The only bad thing is that a database call must be made at some point to gather the description. But the good things are that these values will not be hardcoded.



2. Use Attributes

Like any attributes in .NET, we can define a custom attribute class by defining a class and inheriting the "System.Attribute" base class. However, .NET already provides a DescriptionAttribute class for cases like these in the "System.ComponentModel" namespace.

[Example]

a) Define your enum


    using System.ComponentModel;
 
    public enum FoodItems
    {
        [DescriptionAttribute("A Specialist Bacon Roll")]
        BaconRollWithBurgerSauce = 1,
        [DescriptionAttribute("Burning Hot Chilli")]
        HotChilliBurningHot = 2,
        [DescriptionAttribute("Sixty Inch Pizza with Everything!")]
        SixtyInchPizzaWithEverythingOnIt = 3
    }



b) Use reflection to get the description attribute

// Get the descrption attribute for the status
FoodItem item = FoodItem.BaconRollWithBurgerSauce;
FieldInfo fi = typeof(FoodItem).GetField(Enum.GetName(typeof(FoodItem), item));
DescriptionAttribute da = (DescriptionAttribute)fi.GetCustomAttributes(typeof(DescriptionAttribute), false)[0];
string desc = da.Description;

No comments: