✅ How does CultureInfo works in C#?
Hello guys, it's been quite a few instances now that I came across CultureInfo. I encounted it when comparing strings and when comparing dates. What I understood about it is that, if we don't specify anything, it uses the locale system of our machine. So if our machine is set to
en-us
and we try to compare something with de-DE
, their might be issues here? I know the "ß (Eszett)" stands for "ss" I think... so, what kind of issues might arise?
If we write something like this for eg:
str1 == str2 will return false in this case (If we don't change the CultureInfo thing)?
Now there is also the CultureInfo when we use dates. This is where I'm the most confused. When we use methods like TryParse
with DateOnly, it may happen that the overload contains the IFormatProvider interface, so basically these are "settings" to change the culture specific.
For string I did understand what it does (but please someone confirm if the above statements are correct please.), for date, it's a bit ambiguous though. So say my locale system has culture en-us
, basically, this mean that my date format is specific to the us culture. How will that affect my TryParse
or TryParseExact
?7 Replies
I tried the following code, I don't understand why only 3 dates are valid, what happen internally?
Last question:
Why is it important to put CultureInfo.InvariantCulture here? I obtain the following output only:
10/20/2020
meaning that we only look for the string with the format dd.MM.yyyy
, so if we are already explicitly using a format, why make use of CultureInfo?Only 3 are valid, because "invariant" culture is basically "en-US" with some minor changes, like the currency symbol
For
ParseExact()
the culture does not matter, because you are, well... parsing exactlyoh ok make sense, because I don't see the importance of the culture info here if we are already providing the exact format, I don't see what additional things does it brings.... maybe it's useful in other of its overloads.
When we use CultureInfo.Invariant, behind the scenes, it does use some default settings, like date formats, date separators, etc... ?
Invariant culture simply defines some "generic" patterns, that are not supposed to be associated with any culture
Angius
REPL Result: Success
Console Output
Compile: 402.596ms | Execution: 21.642ms | React with ❌ to remove this embed.
There's more properties like that. Decimal separator, time format, and so on
So, yes, you're correct here
Yepp I see, it's clearer, I understand how all of that works now, thanks !!