enum to string, several custom formats

  • Thread starter Thread starter Wiktor Zychla
  • Start date Start date
W

Wiktor Zychla

I would like to be able to convert enums to their string representation but
I would like to be able to apply a custom formatting, so that I could write
for example:

enum E { a, b, c };

string s1 = E.a.ToString( "d" ); // returns for example 'a'
string s2 = E.a.ToString( "f" ); // returns for example 'this is an enum
value a'

for now I have several methods in special class

class EnumToString
{
string ConvertAToStringD { return ...; }
string ConvertAToStringF { return ...; }
}

but this looks rather ugly.

I've read about EnumConverter class but I am not sure if it is possible to
have several different custom formatting possibilities when using this
class.

could anyone enlighten me?

Thanks in advance.
Wiktor Zychla
 
Hi Wiktor,

I've never used EnumConverters but I looked up the Help topic.

This is how one of these things seems to be used:

Enum eMyBike = eMotorBikes.HondaSuperBlackbird;
string s = "I love to ride my " + TypeDescriptor.GetConverter
(eMyBike).ConvertTo (eMyBike, typeof(string));

Now <that's> what I call ugly!! [not the bike - that's beautiful :-)]

My opinion is that you should do whatever's necessary in your class,
clumsy or not, so that the class's <user> can have pretty code.

Or maybe you want to use the EnumConverter inside your class??

Just some thoughts :-)

Regards,
Fergus
 
string s1 = E.a.ToString( "d" ); // returns for example 'a'
string s2 = E.a.ToString( "f" ); // returns for example 'this is an enum
dobrze jak by sie da³o przeci±¿yæ funkcje w typie wyliczeniowym
ale... sie nie da

mo¿e napisaæ w³asn± klasê formatuj±c± np.:

using System;

public class mF : IFormatProvider, ICustomFormatter
{
public object GetFormat (Type service)
{
if (service == typeof (ICustomFormatter))
{
return this;
}
else
{
return null;
}
}
public string Format (string format, object arg, IFormatProvider
provider)
{
if(format == "F")
{
return "This is an enum value: " + arg.ToString();
}
return String.Format("{0:" + format + "}",arg);
}
}

public enum E
{

a,b,c
}

public class Test
{
//[STAThread]
static void Main()
{
Console.WriteLine(String.Format(new mF(), "{0:S}, {1:F},{2:D}"
,E.c,E.b,E.a));
}
}
 
dobrze jak by sie da³o przeci±¿yæ funkcje w typie wyliczeniowym
ale... sie nie da
exactly.


mo¿e napisaæ w³asn± klasê formatuj±c± np.:

this looks really promising.

thanks ;)
Wiktor
 
Back
Top