Thursday, July 7, 2011

Custom attributes & Enum 2

Display values of custom attribute in Drop Down

Is there any advantage of adding custom attribute in Enum?

I want to bind some Cartoon Character names to drop down box; these values keep as Enum in my project. As we all know Enums doesn’t support spaces and special characters. So… use custom attribute

Method to get Enum as a collection

        public static IEnumerable<CartoonCharacters> GetCommenttype()
{
yield return CartoonCharacters.TinTin;
yield return CartoonCharacters.SpongeBob;
yield return CartoonCharacters.SpiderMan;
yield return CartoonCharacters.BugsBunny;
yield return CartoonCharacters.TomAndJerry;
yield return CartoonCharacters.DonaldDuck;
}

If you think yield keyword is new to you, I found two great articles

Using C# Yield for Readability and Performance
Behind the scenes of the C# yield keyword


Method to bind data
        public static Dictionary<CartoonCharacters, string> GetCartoonCharacters()
{
var list = new Dictionary<CartoonCharacters, string>();

foreach (CartoonCharacters item in GetCommenttype())
{
list.Add(item, GetDescription(item));
}

return list;
}


Don’t forget to bind data collection with drop down
 ddlCartoonCharacters.DataSource = GetCartoonCharacters();
ddlCartoonCharacters.DataTextField = "value";
ddlCartoonCharacters.DataValueField = "key";
ddlCartoonCharacters.DataBind();


Final look

blog

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 &gt; 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(Description), false);

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