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
We can convert an enum to string by calling the ToString() method of an Enum.
The stringify() macro method is used to convert an enum into a string. Variable dereferencing and macro replacements are not necessary with this method. The important thing is that, only the text included in parenthesis may be converted using the stringify() method.
Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.
The Java Enum has two methods that retrieve that value of an enum constant, name() and toString().
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With