In my previous blog I was trying to address the issue that when ToString is called on an enum the literal string for the enum constant is returned. Custom attributes can be used to tag localizable description string to the constants so that you can write functions that use reflection to get to the attribute and show that string. However this has a significant disadvantage as you need to write code as follows

enum Coolness {

[DescriptionAttribute("Not so cool")]

NotSoCool = 5,

[DescriptionAttribute("Very cool")]

VeryCool = NotSoCool + 7,

}

class Program

{

static string GetDescription(Enum en)

{

// Uses reflection to get the attribute and returns it

}

static void Main(string[] args)

{

Coolness coolType = Coolness.VeryCool;

Console.WriteLine(GetDescription(coolType));

}

}

Calling GetDescription method on the enum is definitely not intuitive. This is why I had said that I love extension methods. Converting this to use C#3.0 extension method makes its intuitive and it'll be easy for the developer to remember that in the same lines as ToString there is also a ToDescription on enums.

using System;

using System.Reflection;

using System.Collections.Generic;

using System.Text;

using System.Query;

using System.Xml.XLinq;

using System.Data.DLinq;

using System.ComponentModel;

// C# 3.0 syntax used...

namespace FunWithEnum

{

enum Coolness

{

[DescriptionAttribute("Not so cool")]

NotSoCool = 5,

Cool, // since description same as ToString no attr are used

[DescriptionAttribute("Very cool")]

VeryCool = NotSoCool + 7,

[DescriptionAttribute("Super cool")]

SuperCool

}

static class ExtensionMethods

{

public static string ToDescription(this Enum en) //ext method

{

Type type = en.GetType();

MemberInfo[] memInfo = type.GetMember(en.ToString());

if (memInfo != null && memInfo.Length > 0)

{

object[] attrs = memInfo[0].GetCustomAttributes(
typeof(DescriptionAttribute),

false);

if (attrs != null && attrs.Length > 0)

return ((DescriptionAttribute)attrs[0]).Description;

}

return en.ToString();

}

}

class Program

{

static void Main(string[] args)

{

Coolness coolType1 = Coolness.Cool;

Coolness coolType2 = Coolness.NotSoCool;

Console.WriteLine(coolType1.ToDescription());

Console.WriteLine(coolType2.ToDescription());

}

}

}