ASP.NET Hosting

Associating string values to items in code

In a comment to my previous post about advanced enums, Chris Martin provided code for a custom attribute as a solution.

In fact I use something similar to associate string values to class or class members. See my StringValueAttribute class.
This works the same as Chris' implementation, and allows things like:

enum Colors
{
  [StringValue("#FF000")]
  Red,

  [StringValue("#00FF00")]
  Green,

  [StringValue("#0000FF")]
  Blue
}

Color color = Colors.Red;
Console.Write(StringValueAttribute.GetValue(color));

Too bad we can associate only scalar types, as strings or integers, and not objects...

No Comments