Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormatProvider vs. extension method vs. new class

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).

like image 835
Colin Burnett Avatar asked Nov 05 '22 20:11

Colin Burnett


2 Answers

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.

like image 198
Paul Alexander Avatar answered Nov 13 '22 22:11

Paul Alexander


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.)

like image 44
tim Avatar answered Nov 13 '22 22:11

tim