Adding custom ToString method to Enum

  • Thread starter Thread starter Suresh
  • Start date Start date
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.
 
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.
 
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.


.
 
Back
Top