.netfxcopiformatprovider

Should I always specify which IFormatProvider to use?


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?


Solution

  • 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.