Overriding ToString() for an Enum?

  • Thread starter Thread starter avivgur
  • Start date Start date
A

avivgur

Hi,
Suppose I have an enum declared as:

enum Color {Red, DarkRed, Blue, DarkBlue}
Color c = Color.DarkBlue;

And I want the command "Console.WriteLine(c);" to print out "Dark
Blue" instead of "DarkBlue". In effect, I should probably change the
ToString() method that the enum uses to implement space insertion
between words. The question is, how do I do this?

Thanks,
Aviv.
 
avivgur said:
Hi,
Suppose I have an enum declared as:

enum Color {Red, DarkRed, Blue, DarkBlue}
Color c = Color.DarkBlue;

And I want the command "Console.WriteLine(c);" to print out "Dark
Blue" instead of "DarkBlue". In effect, I should probably change the
ToString() method that the enum uses to implement space insertion
between words. The question is, how do I do this?

You cannot override ToString on an enum. You will have to write another
method to do so and call it when you want an Enum string.
 
In addition to Daniel's comments, you could of course create your own custom
type (and then you could override the tostring) but it would probably be
better to do what Daniel says -it would be much easier and cleaner to do.

--
Best Regards,

Mark

Mark Broadbent

mcad,mcdba,mcse+i
emailto: newsgroupsATmettayyaDOTgotadslDOTcoDOTuk
remove AT with '@' and DOT with '.' -please do not send spam or address will
be changed!
 
Daniel O'Connell said:
You cannot override ToString on an enum. You will have to write another
method to do so and call it when you want an Enum string.


I'm not sure I understand completely...
This other method that you speak of, can it be declared as part of the
enum type to be used as "c.ToNiceString()"? Or does it need to be a
totally seperate method to be incorporated in some helper class?
Moreover, what if I want to send the enum to Console.WriteLine() and
have it written correctly?... keeping in mind that WriteLine() calls
ToString()...

Thanks,
Aviv.
 
I blogged about a mechanism for providing alternative text for an enum. Unfortunately that one entry seems to have problems with me posting a permalink so if you follow this link

http://www.dotnetconsult.co.uk/weblog/CategoryView.aspx/.NET

and scroll down the page to the two entries entitled

"Extending the humble enum" and
"Extending the humble enum (contd)"

You;ll find a technique for providing alternative enum text that used custom attributes.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

I'm not sure I understand completely...
This other method that you speak of, can it be declared as part of the
enum type to be used as "c.ToNiceString()"? Or does it need to be a
totally seperate method to be incorporated in some helper class?
Moreover, what if I want to send the enum to Console.WriteLine() and
have it written correctly?... keeping in mind that WriteLine() calls
ToString()...

Thanks,
Aviv.
 
Back
Top