Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is CultureInfo.CurrentCulture really necessary in String.Format()?

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); 

?

like image 659
abatishchev Avatar asked Jan 24 '09 02:01

abatishchev


People also ask

What is CultureInfo CurrentCulture?

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.

What is the use of CultureInfo InvariantCulture?

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.

What is the use of CultureInfo in C#?

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.


2 Answers

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.

like image 163
Joe Avatar answered Sep 21 '22 17:09

Joe


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.

like image 42
Jeffrey Hantin Avatar answered Sep 18 '22 17:09

Jeffrey Hantin