Enum to String?
<p>I've got an enum defined like this</p>

<pre><code>enum Tile { Empty, White, Black };
</code></pre>

<p>But let's suppose when written to the console, </p>

<pre><code>Console.Write(Tile.White);
</code></pre>

<p>I want it to print</p>

<pre><code>W
</code></pre>

<p><em>Or any other value</em>, I could use a <code>switch</code> for this, but is there a nicer way? Perhaps using attributes?</p>

<hr>

<p>Here's what I have in mind. Writing something like this,</p>

<pre><code>[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)
</code></pre>

<p>Would print</p>

<pre><code>.
</code></pre>

<p>Of course, that <code>override string ToString()</code> didn't do what I was hoping it would do (it still outputs "Empty" instead.</p>

<hr>

<p>This article summarizes it pretty well: <a href="http://blogs.msdn.com/b/abhinaba/archive/2005/10/20/c-enum-and-overriding-tostring-on-it.aspx" rel="nofollow">http://blogs.msdn.com/b/abhinaba/archive/2005/10/20/c-enum-and-overriding-tostring-on-it.aspx</a></p>
