Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum to String?

Tags:

c#

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

like image 571
mpen Avatar asked Sep 02 '10 08:09

mpen


People also ask

Can we convert enum to string?

We can convert an enum to string by calling the ToString() method of an Enum.

Can you convert enum to string C++?

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.

How do I convert string to enum?

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.

Does enum have toString?

The Java Enum has two methods that retrieve that value of an enum constant, name() and toString().


1 Answers

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()); 
like image 135
mathieu Avatar answered Sep 21 '22 00:09

mathieu