Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CA1305: Verbosity when specifying culture

CA1305 is raised when there exists an overload that requires an IFormatProvider but this overload isn't used in the code.

For example, the following code raises this warning:

string.Format("{0} - {1}", id, name);

The obvious way to get rid of this warning is to specify the culture to be used:

string.Format(CultureInfo.InvariantCulture, "{0} - {1}", id, name);

However, I think this is way too verbose.

What alternatives exist?

like image 810
Daniel Hilgarth Avatar asked Oct 22 '12 11:10

Daniel Hilgarth


1 Answers

Pretty much the only alternative that would lead to decreased verbosity while still conserving explicit format provider passing would be to use culture-specific façade methods. Luckily, one typically only formats for InvariantCulture and CurrentCulture, so only two façade methods would be required for each underlying formatting method.

A typical façade method for your sample code might have a signature like this:

public static string FormatForInvariantCulture(this string template, params object[] substitutions)

and be called as follows:

"{0} - {1}".FormatForInvariantCulture(id, name);

Another approach for organizing the façade methods would be into culture-specific formatter types that could be injected using IoC techniques. For example, an interface like the following could be defined for formatting:

public interface IFormatter
{
    string Format(string template, params object[] substitutions);
}

Culture-specific instances could then be injected into types that need to perform formatting using constructors like the following:

public SomeClass(IFormatter systemFormatter, IFormatter uiFormatter)
{
    // ...
}

Regardless of the way the façade methods are packaged, it is important to consider that CA2241 (ProvideCorrectArgumentsToFormattingMethods) will not examine usage of the methods, so it might be worthwhile considering adding a custom rule to do so.

like image 180
Nicole Calinoiu Avatar answered Nov 15 '22 06:11

Nicole Calinoiu