What does CultureInfo.InvariantCulture mean?

JMK picture JMK · Mar 18, 2012 · Viewed 163.3k times · Source

I have a string of text like so:

var foo = "FooBar";

I want to declare a second string called bar and make this equal to first and fourth character of my first foo, so I do this like so:

var bar = foo[0].ToString() + foo[3].ToString();

This works as expected, but ReSharper is advising me to put Culture.InvariantCulture inside my brackets, so this line ends up like so:

var bar = foo[0].ToString(CultureInfo.InvariantCulture)
        + foo[3].ToString(CultureInfo.InvariantCulture);

What does this mean, and will it affect how my program runs?

Answer

JohnB picture JohnB · Mar 18, 2012

Not all cultures use the same format for dates and decimal / currency values.

This will matter for you when you are converting input values (read) that are stored as strings to DateTime, float, double or decimal. It will also matter if you try to format the aforementioned data types to strings (write) for display or storage.

If you know what specific culture that your dates and decimal / currency values will be in ahead of time, you can use that specific CultureInfo property (i.e. CultureInfo("en-GB")). For example if you expect a user input.

The CultureInfo.InvariantCulture property is used if you are formatting or parsing a string that should be parseable by a piece of software independent of the user's local settings.

The default value is CultureInfo.InstalledUICulture so the default CultureInfo is depending on the executing OS's settings. This is why you should always make sure the culture info fits your intention (see Martin's answer for a good guideline).