I've got an enum defined like this
enum Tile { Empty, White, Black };
But let's suppose when written to the console,
Console.Write(Tile.White);
I want it to print
W
Or any other value, I could use a switch for this, but is there a nicer way? Perhaps using attributes?
Here's what I have in mind. Writing something like this,
[AttributeUsage(AttributeTargets.Field)]
public class ReprAttribute : Attribute
{
public string Representation;
public ReprAttribute(string representation)
{
this.Representation = representation;
}
public override string ToString()
{
return this.Representation;
}
}
enum Tile {
[Repr(".")]
Empty,
[Repr("W")]
White,
[Repr("B")]
Black
};
// ...
Console.Write(Tile.Empty)
Would print
.
Of course, that override string ToString() didn't do what I was hoping it would do (it still outputs "Empty" instead.
This article summarizes it pretty well: http://blogs.msdn.com/b/abhinaba/archive/2005/10/20/c-enum-and-overriding-tostring-on-it.aspx