Beware when comparing CultureInfo instances

by ingvar 2. July 2010 10:04

Because CultureInfo is a class and not a struct, the usage of == and != will almost always yield non expecting results. Please take a look at the following code:

CultureInfo cultureInfo1 = CultureInfo.CreateSpecificCulture("en-US");
CultureInfo cultureInfo2 = CultureInfo.CreateSpecificCulture("en-US");
bool result1 = cultureInfo1 == cultureInfo2; /* false!!! */
bool result2 = cultureInfo1.Equals(cultureInfo2); /* true, as expected. */

Unlike many other type in the runtime (string, int, DateTime, TimeSpan, Guid etc) CultureInfo is a class and not a struct. And CultureInfo does not have any overloads for ==/!=, so the usage of == and != will do a reference comparison and NOT a value comparison.

The morale of this is; always use the CultureInfo.Equals method when comparing CultureInfo instances. And yes, if you really mean to do a reference comparison, then you of cause use the ==/!= operators.

Tags: ,


About the author

Martin Ingvar Kofoed Jensen

Architect and Senior Developer at Composite on the open source project Composite C1 - C#/4.0, LINQ, Azure, Parallel and much more!

Follow me on Twitter

Read more about me here.

Read press and buzz about my work and me here.

Stack Overflow

Month List