CodeSweatAndBeers

Using .NET 2.0, is it possible to apply a custom formatter to an enumerated type For example, if I had the following enumeration:

Public Enum Holiday
None = 0
NewYearsDay
StPatricksDay
AprilFoolsDay
End Enum

Is it possible to create a custom formatter that would allow me to print the names of the members with spaces between the words For example,

Holiday.NewYearsDay.ToString("s") 'The 's' is a custom format specifier...
'Ideally, the line above should cause a custom formatter to be used that returns the string "New Year's Day" (note the spaces between the words and the apostrophe between the r and s).

I have successfully created custom formatters for objects, but never enums. Can anyone offer any advice on this matter

Thanks



Re: .NET Base Class Library Custom formatters and enumerated types

nobugz

You could do this with a TypeConverter. For example:

using System;
using System.Collections;
using System.ComponentModel;

[TypeConverter(typeof(HolidayConverter))]
public enum Holiday {
None,
NewYearsDay,
StPatricksDay,
AprilFoolsDay
}

public class HolidayConverter : EnumConverter {
public HolidayConverter() : base(typeof(Holiday)) {
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) {
if ((destinationType == typeof(string)) && (value is Holiday)) {
switch ((Holiday)value) {
case Holiday.None: return "Work, work, work :|";
case Holiday.NewYearsDay: return "Out with the old!";
case Holiday.StPatricksDay: return "Only Irish do dad";
case Holiday.AprilFoolsDay: return "Easter's next";
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
}

You would use the converter like this:

Holiday day = Holiday.NewYearsDay;
TypeConverter cvt = TypeDescriptor.GetConverter(day);
Console.WriteLine(cvt.ConvertTo(day, typeof(string)));






Re: .NET Base Class Library Custom formatters and enumerated types

UsuallyPrettyKnowledgeable

Thanks for the response.

That's definitely a good option (and possibly the only way to do it). I was hoping to find some way to harness the power of the ToString() method, but this will have to do. In any event, you provided me with a good example of a TypeConverter implementation which will definitely come in handy down the road! Thanks again!

If anyone else has a suggestion on a way to utilize the ToString() method, I'm definitely interested!