Enum to String?

Viewed 50201

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

8 Answers

I suggest a combination of the enum and a static Dictionary (and an extension method).

It will avoid the (expensive) reflection and has a clean structure. You can optimize the naming further to make it even more convenient.

public enum OrderStatus
{
    Ready,
    InProduction,
    Completed
}

public static class EnumRelations
{
    public static Dictionary<OrderStatus, string> OrderStatusToString = new Dictionary<OrderStatus, string>()
    {
        { OrderStatus.Ready, "Ready" },
        { OrderStatus.InProduction, "In Production" },
        { OrderStatus.Completed, "Completed" },
    };
}

public static string GetEnumString(this OrderStatus os)
{
    var str = OrderStatusToString[os];
    return str;
}

var str = OrderStatus.Ready.GetEnumString();
Related