Could anybody give an example to demonstrate the usage of the Invariant Culture? I don't understand what the documentation describes.
The invariant culture is a special culture which is useful because it will not change. The current culture can change from one user to another, or even from one run to another, so you can't rely on it staying the same.
Being able to use the same culture each time is very important in several flows, for example, serialization: you can have 1,1 value in one culture and 1.1 in another. If you will try to parse "1,1" value in the second culture, then parsing will fail. However you can use the invariant culture to convert a number to a string and later parse it back from any computer with any culture set.
// Use some non-invariant culture.
CultureInfo nonInvariantCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = nonInvariantCulture;
decimal dec = 1.1m;
string convertedToString = dec.ToString();
// Simulate another culture being used,
// following code can run on another computer.
nonInvariantCulture.NumberFormat.NumberDecimalSeparator = ",";
decimal parsedDec;
try
{
// This fails because value cannot be parsed.
parsedDec = decimal.Parse(convertedToString);
}
catch (FormatException)
{
}
// However you always can use Invariant culture:
convertedToString = dec.ToString(CultureInfo.InvariantCulture);
// This will always work because you serialized with the same culture.
parsedDec = decimal.Parse(convertedToString, CultureInfo.InvariantCulture);