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);
?
The CultureInfo. CurrentCulture property is a per-thread setting; that is, each thread can have its own culture. You get the culture of the current thread by retrieving the value of the CultureInfo. CurrentCulture property, as the following example illustrates. C# Copy.
The InvariantCulture property can be used to persist data in a culture-independent format. This provides a known format that does not change and that can be used to serialize and deserialize data across cultures.
The CultureInfo class provides culture-specific information, such as the language, sublanguage, country/region, calendar, and conventions associated with a particular culture. This class also provides access to culture-specific instances of the DateTimeFormatInfo, NumberFormatInfo, CompareInfo, and TextInfo objects.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With