views:

55

answers:

3

I am revising for the MCTS example and am on a small section regarding Culture-Insensitive comparisons. I get the principle, you don't two items which are the same (i.e dates) but are displayed differently and hence are pragmatically marked as different.

However call me stupid but I am finding it hard to see where I can use it is practice, for example why would you have two different date times, in the same code, in which they are different cultures? The only way to do so would be if you manually override the one of the datatypes cultures and why would you do that?

Any example of a real-world application of culturally insensitive comparisons?

Cheers

+2  A: 

You may want to compare a user input (which can be in different cultures) with a reference string set in code.

One of the classic use-cases for culture invariant comparisons is the Turkish-I problem. Assume that you have a textbox in your application that validates a URL protocol by checking whether it starts with http://, ftp://, or file://. If you write:

inputUrl.StartsWith("FILE://", StringComparison.CurrentCultureIgnoreCase)

and the user input is file://test, it'll work on a machine with English regional settings (more accurately, the thread's CurrentCulture) but the test will fail if the culture is set to Turkish because the uppercase version of file:// will be FİLE:// in Turkish alphabet.

In these cases, we want to match the string using invariant culture:

inputUrl.StartsWith("FILE://", StringComparison.InvariantCultureIgnoreCase)

In general, when you want to perform comparisons for input data where the input has specific semantics in your program (it represents a URL, resource key, ...) rather than simply being used for display purposes or storage and retrieval, you should consider using InvariantCulture.

Mehrdad Afshari
A: 

Think about a localized web site. in US the date convention is mm/dd/yyyy and in Europe the convention is dd/mm/yyyy.

tsinik
A: 

for example why would you have two different date times, in the same code, in which they are different cultures?

One way is if you persist a DateTime value somewhere (a file, the registry). If two users with different cultures access the same file / registry entry, you want it to be in a format that is independent of their culture.

Joe