What is the best way to compare two CultureInfo instances?
Asked Answered
T

1

15

Background:

I have a problem with a component, which changes the current thread culture to "en-US" every time after a call to a specific method of it. Further in my process that leads to problems, e.g. the data access layer is no more working because SqlParameter's CultureInfo gets also changed to "en-US", thus a given string can't be parsed no more to a DateTime SqlValue.

Possible solution:

So the idea is to backup the threads current culture before and restore it afterwards the call to the specific method which changes the current threads culture. When restoring the culture first i check for the culture if it has changed at all.

The Problem/Question:

I could compare the backuped CultureInfo.Name with Thread.CurrentThread.CurrentCulture.Name but I could also use the .Equals() method of the CultureInfo instance. Which is the better way for comparing two CultureInfo instances? Is there maybe a third/better solution?

Tremain answered 25/6, 2014 at 15:41 Comment(0)
H
17

You should use (as it is overloaded for comparing CultureInfo instances)

bool result2 = cultureInfo1.Equals(cultureInfo2); 

As shown in this blog: http://www.toolheaven.net/post/2010/07/02/Beware-when-comparing-CultureInfo-instances.aspx

Haggadist answered 25/6, 2014 at 16:0 Comment(3)
Yes, .Equals() is overloaded and i tested two instances of e.g. CultureInfo("de-DE"), where i changed a property of one of the two objects and afterwards called Equals() -> it also returned true - ok. I just wanted to make sure :-) I'll set your answer as accepted. But i think for my use case it's absolutely sufficient to compare the .Name properties. Maybe you have some concerns with that approach? :-) Thanks.Tremain
Have a look at referencesource.microsoft.com/#mscorlib/system/globalization/… where you can see how microsoft implemented equals. Its ckmparing the names and compareinfoHaggadist
Just an information for people having similar problems: CultureInfo.DateTimeFormat Property ist not checked in CultureInfo.Equals()! Thus it doesn't help me with my special problem because the changed DateTimeFormat property leads to converting error of string to datetime in my DAL.Tremain

© 2022 - 2024 — McMap. All rights reserved.