I tried running FxCop on a few assemblies of our product, and I get lots and lots of matches of the "Specify IFormatProvider" rule.
As it happens, some of those are legitimate, but it also matches code like this:
Logger.DebugFormat("Appending file {0}", fileName);
Which can be written as
Logger.DebugFormat(CultureInfo.InvariantCulture, "Appending file {0}", fileName);
The second variant is much harder to read.
So, is it actually recommended to always specifiy the IFormatProvider
or is it "just" a limitation of the heuristic used in the rule?
It only applies to methods with an IFormatProvider
overload.
To deal with this problem, I have two static classes, InvariantText
and CulturedText
, that work with strings in the invariant culture and current culture, respectively. For example, I have a Format method in each class. This way, I can do culture-neutral and culture-aware formatting without having to specify an IFormatProvider
each time.
Example:
InvariantText.Format("0x{0:X8}",value);
CulturedText.Format("Appending file {0}",file);
InvariantText.Format
and CulturedText.Format
are simply wrappers to the String.Format
method, and accordingly likewise return strings.
You can even use this pattern to wrap other functions that require culture-neutral and culture-specific strings. For example, create two methods, InvariantLog
and CulturedLog
that wrap calls to Logger.DebugFormat
in your question and take the appropriate IFormatProvider
in each case.
It depends. You are aware how and where application will be used, so please consider following MSDN recommendations:
PS: I believe FxCop
follows the third rule and let you specify the right culture yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With