views:

197

answers:

3

I was wanting to output an integer to roman numerals and ran across this answer by Jesse Slicer. It is an extension method, but I was wondering about taking advantage of ToString(string, IFormatProvider) to do something like

int a = 10;
string b = a.ToString("RN", provider);
// OR
string c = string.Format(provider, "{0:RN} blah foo", a);

instead of

int a = 10;
string b = a.ParseRomanNumeral();
// OR
string c = string.Format("{0} blah foo", a.ParseRomanNumeral());

I have never written a format provider so I'm not sure of the work involved but here's my question. For some well-defined format conversion like Roman numerals, would you use:

  • a format provider
  • use an extension method
  • write a RomanNumeral class that implements Parse, TryParse, and ToString
  • something else

and why?

Does using string.Format() and any of its cousin methods (e.g., StringBuilder.AppendFormat()) affect your answer? Obviously with extension methods you couldn't access the conversion using one of these formatting methods.

I would think a custom class to implement the whole gamut would be most prudent but also the most time consuming. Going with the custom format provider seems like it would step on the toes of some existing globalization stuff (if you have any).

A: 

I guess it depends on how you intend to use this functionality.

IMO, extension method is a good way to go. Not sure, how users of your assembly working with c# 1 or 2 (language without support of extension methods) will see it.

Extension methods both ways will be good.
i.e. on numeric types - to convert from number to Roman and
on string - to convert from Roman to number (you will have to consider a numeric type which should accomodate the max value).

shahkalpesh
Extension methods negate the ability to use String.Format, correct?
Colin Burnett
Not really. But, how will format work when converting from string to roman numerals in terms of code?
shahkalpesh
String.Format wouldn't be for string to number conversion (it can't). This is why I think a RomanNumeral class covers all the uses most elegantly.
Colin Burnett
+1  A: 

Format providers work well for your own types, but they're clumsy when using built in types cause you have to create an instance of the provider and pass it to the Format method which eliminates the advantage of the format specifier. It's much more convenient to use an extension method directly on the int.

Paul Alexander
+1  A: 

Personally, I'd write a roman numeral class, with tryparse, parse + tostring(), with extension methods to support it, for a combination of all the reasons above (including your latter comment to shahkalpesh's answer.)

tim