mr_plum
mr_plum

Reputation: 2437

Handling CultureInfo in String.Format()

I'm trying to satisfy all FxCop rules in a new library. As such, I need to specify an IFormatProvider for all my String.Format() calls. Example:

public string Example(string value) {
    return string.Format(CultureInfo.CurrentCulture, 
                         "You entered: {0}", value);
}

It gets very tedious specifying CultureInfo hundreds of times, so I made a helper:

public string Example2(string value) {
    return CurrentCulture("You entered: {0}", { value });
}

private string CurrentCulture(string value, object[] objects) {
    return string.Format(CultureInfo.CurrentCulture, value, objects);
}

This works, but I lose all my Resharper warnings if I malform the "You entered: {0}", { value } part.

Perhaps it's best to just use a short alias:

public string Example3(string value) {
    return string.Format(Current(), "You entered: {0}", value);
}

private CultureInfo Current() {
    return CultureInfo.CurrentCulture;
}

Any other ideas?

Upvotes: 2

Views: 1299

Answers (1)

Christian.K
Christian.K

Reputation: 49260

I would actually go with the wrapper methods. You can retain your ReSharper warnings, when you attribute your methods with the JetBrains.Annotations.StringFormatMethodAttribute of ReSharper.

Update I missed the params keywoard in the signature. Thanks to @EricMSFT for the comment/hint.

[StringFormatMethod("value")]
private string CurrentCulture(string value, params object[] objects) {
    return string.Format(CultureInfo.CurrentCulture, value, objects);
}

The easiest way (there are others like defining the StringFormatMethodAttribute in your own codebase) is probably to just reference "C:\Program Files (x86)\JetBrains\ReSharper\v6.1\Bin\JetBrains.Annotations.dll" in your project.

More details here.

Upvotes: 1

Related Questions