Thursday, July 7, 2011

Custom attributes & Enum

Formal introduction to Enum: provides an efficient way to define a set of named integral constants that may be assigned to a variable.

As we use enums in our day today life, we may need small improvements and additional things integrated with enums.

This is my Enum (without custom attribute)

public enum CartoonCharacters
{
TinTin = 1,
SpongeBob = 2,
SpiderMan = 3,
BugsBunny = 4,
TomAndJerry = 5,
DonaldDuck = 6
}



I’m going to integrate descriptive text (some extra values) with my CartoonCharacters enum.

Enum with Description


public enum CartoonCharacters
{
[Description("Tin Tin")]
TinTin = 1,

[Description("Sponge Bob")]
SpongeBob = 2,

[Description("Spider Man")]
SpiderMan = 3,

[Description("Bugs Bunny")]
BugsBunny = 4,

[Description("Tom And Jerry")]
TomAndJerry = 5,

[Description("Donald Duck")]
DonaldDuck = 6
}

public class Description : Attribute
{
public string Text;

public Description(string text)
{
Text = text;
}
}



  Method to read the description


    public static string GetDescription(Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());

if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(Description), false);

if (attrs != null && attrs.Length > 0)
return ((Description)attrs[0]).Text;
}
return en.ToString();
}

No comments:

Post a Comment