Tuesday, June 29, 2010

Underused C# feature: string.Format and custom formatters

There are developers out there who get classified as being lazy. I got called being a lazy developer when adding an Extension method to decimal types to convert to some Html formatted string.


This makes the code look clean and is pretty simple to understand for any other developer to come in later and know what is being done. The problem is that other developers may consider this abuse or misuse of Extension methods. "Why should a decimal know how to convert itself into a certain type of string?"

Enter the string.Format method and a custom formatter. string.Format can take in any argument, a format, and custom formatter, then return you the string equivalent for that argument. Although I agree that this is a more appropriate approach that doesn't make it a cleaner solution. In my opinion only.

You would make the call like this:

Although it works and is the proper solution in this case, it's ugly.

I am open to other solutions to this scenario, so if you have a good solution please post in the comments.

Here is a full example of how to implement a custom formatter to use with string.Format.

Test Class (MS Test):

Custom formatter implementation example:


  1. That's a lot of extra markup for basically a ToString overload. The base object knows how to turn itself into a string, so why can't a decimal?

    Is possible to override the decimal class's ToString method?

  2. You would only be able to override the ToString method if decimal was a base class to a new object that you created. Hence the extension method.

    Now you could also create another class called "Price" in this example. It's constructor could require a decimal, then "Price's" ToString method could return you the result based on a passed format.