Overriding ToString() in an enumeration

  • Thread starter Thread starter Neil
  • Start date Start date
N

Neil

Is it possible to override the ToString() method when
creating a simple enumeration?

public enum myEnum {
Undefined = 0,
Unassigned = 1,
Assigned = 2,
Reallocated = 3
}

I would like to be able to apply some extended features to
the ToString().

Thanks.
 
You won't be able to this for an enum in C#. You could create a class with
member fields as the values and override ToString() there, however. This
would be easy and have vritually the same syntax as an Enum.

Richard
 
Here is the code again:

http://www.geocities.com/jeff_louie/OOP/oop5.htm

sealed class MyEnum
{
    private String name;
    private static int nextOrdinal= 1;
    private int ordinal= nextOrdinal++;
    private MyEnum(String name)
    {
        this.name= name;
    }
    public override String ToString()
    {
        return name;
    }
    public int ToOrdinal()
    {
        return ordinal;
    }
    public static MyEnum INVALID= new MyEnum("Invalid"); // ordinal 1
    public static MyEnum OPENED= new MyEnum("Opened"); // ordinal 2
    public static MyEnum CLOSED=new MyEnum("Closed"); // ordinal 3
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        //
        // TODO: Add code to start application here
        //
        Console.WriteLine(MyEnum.OPENED.ToString());
        Console.WriteLine(MyEnum.OPENED.ToOrdinal().ToString());
        Console.WriteLine(MyEnum.INVALID.ToString());
        Console.WriteLine(MyEnum.INVALID.ToOrdinal().ToString());
        Console.WriteLine(MyEnum.CLOSED.ToString());
        Console.WriteLine(MyEnum.CLOSED.ToOrdinal().ToString());
        Console.ReadLine();
    }
}

Regards,
Jeff
Is it possible to override the ToString() method when
creating a simple enumeration?<
 
Back
Top