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.

Example:


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: