views:

2569

answers:

4

Hi.

How do you think is really necessary to provide IFormatProvider in method String.Format(string, object) ?

Is it better to write full variant String.Format(CultureInfo.CurrentCulture, "String is {0}", str) or just String.Format("String is {0}", str) ?

+2  A: 

It is especially useful if you care about localization (Globalization) in your application. That is, if you want your app to support multiple languages and culture specific formats, then you should use that.

Ian P
+2  A: 

No, you do not need to specify the culture unless your string contains culture specific elements such as decimal separators, currency, etc., which have to be rendered depending on the culture.

Spikolynn
+5  A: 

If you do not specify the IFormatProvider (or equivalently pass null) most argument types will eventually fall through to being formatted according to CultureInfo.CurrentCulture. Where it gets interesting is that you can specify a custom IFormatProvider that can get first crack at formatting the arguments, or override the formatting culture depending on other context.

Note that CultureInfo.CurrentCulture affects argument formatting, not resource selection; resource selection is controlled by CultureInfo.CurrentUICulture.

Jeffrey Hantin
Thanks for setting me straight. I removed my post as it was misleading.
Chris Lively
+5  A: 

In general, you will want to use InvariantCulture if the string you are generating is to be persisted in a way that is independent of the current user's culture (e.g. in the registry, or in a file).

You will want to use CurrentCulture for strings that are to be presented in the UI to the current user (forms, reports).

Subtle bugs can arise if you use CurrentCulture where you should be using InvariantCulture: bugs that only come to light when you have multiple users with different cultures accessing the same registry entry or file, or if a user changes his default culture.

Explicitly specifying CurrentCulture (the default if the IFormatProvider argument is omitted), is essentially documentation that demonstrates that you have considered the above and that the string being generated should use the current user's culture. That's why FxCop recommends that you should specify the IFormatProvider argument.

Joe