Enum to String?
The naive non-attribute way:
public enum Tile {
White = 'W',
Black = 'B'
}
//...
System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}", Tile.White.ToString(), (char)Tile.White));
//Prints out:
//White - W
You could use attributes :
using System.ComponentModel;
public enum Tile
{
[Description("E")]
Empty,
[Description("W")]
White,
[Description("B")]
Black
}
And an helper method :
public static class ReflectionHelpers
{
public static string GetCustomDescription(object objEnum)
{
var fi = objEnum.GetType().GetField(objEnum.ToString());
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : objEnum.ToString();
}
public static string Description(this Enum value)
{
return GetCustomDescription(value);
}
}
Usage :
Console.Write(Tile.Description());
You can use the ToString() method:
Tile t = Tile.White;
Console.WriteLine(t.ToString()); // prints "White"
Console.WriteLine(t.ToString().SubString(0, 1)); // prints "W"