Should I always indicate which IFormatProvider to use?

I tried running FxCop on several builds of our product, and I get many, many matches in the "Define IFormatProvider" rule.

As it happens, some of them are legal, but it also matches code like this:

Logger.DebugFormat("Appending file {0}", fileName); 

What can be written as

 Logger.DebugFormat(CultureInfo.InvariantCulture, "Appending file {0}", fileName); 

The second option is much harder to read.

So, is it really advisable to always specify an IFormatProvider or is it a β€œjust” heuristic restriction used in a rule?

+4
source share
3 answers

It applies only to methods with IFormatProvider overload.

To deal with this problem, I have two static classes: InvariantText and CulturedText , which work with strings in the invariant culture and the current culture, respectively. For example, I have a Format method in each class. That way, I can do culture-neutralizing and culture- IFormatProvider formatting without having to specify an IFormatProvider every time.

Example:

 InvariantText.Format("0x{0:X8}",value); CulturedText.Format("Appending file {0}",file); 

InvariantText.Format and CulturedText.Format are simply wrappers of the String.Format method and return strings accordingly.


You can even use this template to transfer other functions that require culture-neutral and culture-specific strings. For example, create two methods: InvariantLog and CulturedLog , which complete the Logger.DebugFormat calls in your question and accept the corresponding IFormatProvider in each case.

+6
source

It depends. You know how and where the application will be used, so please consider the following MSDN recommendations:

PS: I believe that FxCop follows the third rule and allows you to specify the right culture on your own.

+2
source

The rule is not the only reader of your code. Unless you explicitly specify a formatting culture, the service developer will not be able to distinguish between intentionally disconnecting from the default formatting culture (CurrentCulture in most cases) or an omission that could lead to incorrect formatting. If you don't like verbosity, consider wrapping methods similar to those suggested by Peter O.

+1
source

All Articles