While porting old C code to C#, I stumbled across lots of huge arrays which mapped constants to strings. While looking for the C# way of doing this, I discovered custom attributes and reflection.
How is it done?
Description attribute to each enum entry:
private enum MyColors
[Description("yuk!")] LightGreen = 0x012020,
[Description("nice :-)")] VeryDeepPink = 0x123456,
[Description("so what")] InvisibleGray = 0x456730,
[Description("no comment")] DeepestRed = 0xfafafa,
[Description("I give up")] PitchBlack = 0xffffff,
To access the description from code, the following function is called:
public static string GetDescription(Enum value)
FieldInfo fi= value.GetType().GetField(value.ToString());
DescriptionAttribute attributes =
Without the following
using declaration, the code will not compile.
Instead of having constants and huge arrays all over the code, the above solution keeps declarations and descriptions nicely together.
I've only found out by accident that the framework already provides a
I built the first version with my own custom attribute and got conflicts when I started using the
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.