NovelProjects

Wednesday, January 13, 2010

C# custom Attribute on an enum object

Today I was working with an enum on a class object and I wanted something more than just the default MyObject.MyEnum.ToString() (which returns the name of my enum as defined in code). Here was my enum:


public enum ImportType
{
FullProduct = 1,
ImageProduct = 2,
PriceProduct = 3,
Customer = 4
}

I wanted something more descriptive and readable than 'FullProduct' so I asked my good buddy Google. That lead me to this article. After adding in a couple classes my enum now looks like:

public enum ImportType
{
[Description("Full Product Import")]
FullProduct = 1,
[Description("Product Image Import")]
ImageProduct = 2,
[Description("Product Price Import")]
PriceProduct = 3,
[Description("Customer Import")]
Customer = 4
}

Now on my front end I can call


<%# EnumHelper.GetDescription((ImportType)Eval("Type")) %>

and get 'Full Product Import' instead of 'FullProduct'