overriding ToString () method for enumerations in C#

Hallo

I have to override the ToString () method of an enumeration. How is the syntax in C# to do that Can someone help me
Thanks
Franz




Answer this question

overriding ToString () method for enumerations in C#

  • Seshu Palachulla

    Franz,

    Unfortunately it's not possible to override ToString() on a enumeration. Instead, you need to provide a helper method to do this:



    public static string ToString(MyEnum value)
    {
    return "This is my customized ToString():" + value.ToString();
    }



  • frozennose

    Sorry that I had misunderstood the question previously. Now I know that you cannot override ToString() method in enumerations. You have to write some utility functions to do so.


  • TGAR

    You might want to take a look at the [Flag] attribute, which gives you a cheap ToString() override (albeit to the name of the enumerated value):

    http://msdn.microsoft.com/library/default.asp url=/library/en-us/cpref/html/frlrfsystemflagsattributeclasstopic.asp

  • tom-b

    Hallo rabin

    your example overrides the ToString() method of a class.
    But I have to override the method of an enumeration type.


    My example:

    class ImportItem
    {
      public enum ImportState { ImportIt, DontImportIt, Importing, Imported, ImportFailed }

      public ImportState State { get { return mState; } }
      private ImportState mState;

      .....
    }

    class Test
    {
      public static void Main ()
      {
         ImportItem Item = new ImportItem ();
         .....
         Console.WriteLine (Item.State);
      }
    }


    This will output "ImportIt", but I would like to override ToString () such that it outputs i.e. "Import required".

    Thanks for a tip
    Franz




  • overriding ToString () method for enumerations in C#