Enum's with custom ToString()

Topics: C# Language Design
Apr 22, 2014 at 9:59 AM
Hi!

Sometimes it would be nice to override the ToString() method of the members of an enumeration. Simple examples are the use in a ComboBox etc., where the ToString() method is used to show it to the user, therefore the output is always restricted (no white spaces, no special characters etc.) I used Attributes and a wrapper class that contains the enum value and a ToString() method with respect to the attribute. It works, but it is a workaround.

In Java, it is possible to overwrite the ToString() method. Look at the following example that I have taken from http://javahowto.blogspot.de/2006/10/custom-string-values-for-enum.html
public enum MyType {
ONE {
     public String toString() {
        return "this is one";
      }
  },
TWO {
    public String toString() {
        return "this is two";
    }
 }
}
It would be nice to have a similar feature in C# as well.
Apr 22, 2014 at 11:08 AM
I think better to add methods into enums:
As I know enums is some sort of class and it can has methods, properties...
public enum SomeEnum
{
   ONE, 
   TWO,

   public override String ToString( )
   {
      switch( value )
      {
      case ONE: return "this is one";
      case TWO: return "this is two";
      }
   }

   public static implicit AnotherEnum( SomeEnum value )
   {
      ...
   }
}
Apr 22, 2014 at 1:14 PM
I've wanted this kind of thing in C# for a long time. I'd be interested to hear from a language designer if this kind of thing is even possible to layer on top of the existing enum infrastructure in C# or would a whole new special type need to be added.
Apr 23, 2014 at 1:33 PM
I need improved enums, too.
Even though we can use kind of thing with attribute extension method(not good), I think today's C# enum system is weak. For example, String to Enum convert method is not generic one.
So enums should be improved not only ToString() but also enum system.
Apr 27, 2014 at 1:30 PM
You can have a static class with string constant values:

public static class SomeEnum {
    public const string ONE = "this is one";
    public const string TWO = "this is two";
}
There is TypeConverter class that is designed to be used in your scenario. In XAML you can do IValueConverter. There are plenty of tools available.
Apr 27, 2014 at 7:52 PM
@Galich This is not the same as having more powerful enums.
public static class SomeEnum {
    public const string ONE = "this is one";
    public const string TWO = "this is two";
}

public void PrintMe(SomeEnum e)  //This doesn't work. You can't have strong typing here without an enum
{
    Console.WriteLine(e);
}