Formatting strings in C # sequentially throughout a large web application

I am looking for a consistent way to structure the use of formatting strings in a large web application, and I am looking for recommendations or recommendations on how to do this.

So far I have had a static class that does some general formatting, for example.

Formatting.FormatCurrency

Formatting.FormatBookingReference

I'm not sure if this is the way to go, but I would prefer to use the standard way to format strings in .NET directly and use:

amount.ToString ("c")

reference.ToString ("000000")

Id uses IFormattable and ICustomFormatter for some of our more complex data structures, but I'm afraid of what to do with simpler existing objects that we need to format (in this case, Int32, as well as DateTime).

Am I just defining constants for "c" and "000000" and using them consistently around the entire web application or is there a more standard way to do this?

+4
source share
3 answers

One option is to use a helper class with extension methods such as

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

Then anywhere, you have a decimal value that you do

 Decimal d = 100.25; string s = d.FormatCurrency(); 
+12
source

I agree with GeekyMonkey's suggestion with one change:

Formatting is an implementation detail. I would suggest ToCurrencyString to adhere to the To * convention and its intentions.

+5
source

This answer can be combined with a GeekyMonkey answer.

First of all, in ASP.NET you have the opportunity to set the culture and culture of the user interface in web.config using the globalization element. The resourceProviderFactoryType attribute is your friend when you have special formatting needs.

Another possibility is to subclass the ASP.NET page class and override the InitializeCulture method. Here you can change the culture and culture of the user interface, which is stored in the current stream that processes the HTTP request.

Quick example:

 protected override void InitializeCulture() { Thread.CurrentThread.CurrentCulture = ...; Thread.CurrentThread.CurrentUICulture = ...; Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy"; ... } 

For those who worry that ASP.NET performs "random" thread switching:

ASP.NET ensures that even if they switch the stream, the CurrentPrincipal and culture properties from the source stream are transferred to the new stream. This is automatic and you don’t need to worry about losing these values. Phew!

Source: ASP.NET Thread Switching

+2
source

All Articles