Adding custom ToString method to Enum

S

Suresh

Hi,
I need to add a custom ToString method on an Enum
Property. The default ToString method expands the whole
name. But, I want only an short associated code with the
long name of the enum type.

For example,
public enum Color { Red = 0, Blue, Green }

The statement

Color cr = Color.Red;
Console.WriteLine(cr.ToString());

prints, "Red". But, I want to override ToString of Color
to yeild a result "RD" for red. "BL" for Blue and "GR" for
green.

Can anyone help me out?

Thanks and Best Regards
Suresh.
 
N

Nicholas Paldino [.NET/C# MVP]

Suresh,

You are not going to be able to do this. The reason for this is that
you can not extend structures so you can not override the ToString method.

What I would do is create a class that derives from TypeConverter, and
then override the ConvertFrom and ConvertTo methods. You can then transform
your color to your code based the color passed in. You would then
instantiate an instance of this class and then call the appropriate methods
(ConvertFromString and ConvertToString, these methods will end up calling
the ConvertFrom and the ConvertTo methods).

Hope this helps.
 
S

Suresh

Thanx Nich.

That exactly solved my problem.

Instead I used EnumCoverter class.

Best Regards
Suresh.
-----Original Message-----
Suresh,

You are not going to be able to do this. The reason for this is that
you can not extend structures so you can not override the ToString method.

What I would do is create a class that derives from TypeConverter, and
then override the ConvertFrom and ConvertTo methods. You can then transform
your color to your code based the color passed in. You would then
instantiate an instance of this class and then call the appropriate methods
(ConvertFromString and ConvertToString, these methods will end up calling
the ConvertFrom and the ConvertTo methods).

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Hi,
I need to add a custom ToString method on an Enum
Property. The default ToString method expands the whole
name. But, I want only an short associated code with the
long name of the enum type.

For example,
public enum Color { Red = 0, Blue, Green }

The statement

Color cr = Color.Red;
Console.WriteLine(cr.ToString());

prints, "Red". But, I want to override ToString of Color
to yeild a result "RD" for red. "BL" for Blue and "GR" for
green.

Can anyone help me out?

Thanks and Best Regards
Suresh.


.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top