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.
Format.Invariant("{0} - {1}", id, name)
andFormat.ForUI
. The problem is that this only solvesstring.Format
. It wouldn't solve any other case of this warning... – Fourway