Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting strings in C# consistently throughout a large web application

I'm looking for a consistent way to structure my use of formatting strings throughout a large web application, and I'm looking for recommendations or best practices on which way to go.

Up until now I've had a static class that does some common formatting e.g.

Formatting.FormatCurrency

Formatting.FormatBookingReference

I'm not convinced that this is the way to go though, I'd prefer to use the standard way of formatting strings within .NET directly and use:

amount.ToString("c")

reference.ToString("000000")

Id use IFormattable and ICustomFormatter for some of our more complicated data structures, but I'm struggling what to do about the more simple existing objects that we need to format (in this case Int32 but also DateTime).

Do I simply define constants for "c" and "000000" and use them consistently around the whole web app or is there a more standard way to do it?

like image 534
Kieran Benton Avatar asked Dec 02 '22 08:12

Kieran Benton


2 Answers

One option is to use a helper class with extension methods like

public static class MyWebAppExtensions
{
    public static string FormatCurrency(this decimal d)
    {
        return d.ToString("c");
    }
}

Then anywhere you have a decimal value you do

Decimal d = 100.25;
string s = d.FormatCurrency();
like image 161
GeekyMonkey Avatar answered Dec 03 '22 22:12

GeekyMonkey


I agree with GeekyMonkey's suggestion, with one alteration:

Formatting is an implementation detail. I would suggest ToCurrencyString to keep with the To* convention and its intent.

like image 44
Bryan Watts Avatar answered Dec 03 '22 21:12

Bryan Watts