This post continues on the Dev Info from the previous post.
The confusion over what string comparator to use is close second to the #1 coding confusion (mix up between CultureInfo.InvariantCulture and CultureInfo.CurrentCulture) mentioned earlier. MSDN has a good detailed article on this here and below is just my summary of the same to increase awareness.
What is StringComparison?
Specifies the culture, case, and sort rules to be used by certain overloads of the String.Compare and String.Equals methods. Corresponding to each StringComparison value, there is StringComparer that can be used too for various string comparison functionality.
For example –
// Here the result will be always TRUE bool result = string.Equals("string", "STRING", StringComparison.OrdinalIgnoreCase); // Here the result will be TRUE for most cultures but for culture like Turkish // it will be false. Turkish has four i's. bool result = string.Equals("string", "STRING", StringComparison.OrdinalIgnoreCase);
English vs. Turkish Case Mappings
Language
Letter
Lowercase Map
Uppercase Map
English
i
I
Turkish
dotted i
İ
dotless ı
ı
StringComparison member
Description
When to use
Ordinal
Performs an ordinal comparison.
· Case-sensitive identifiers in standards such as XML and HTTP.
· Case-sensitive security-related settings.
· Other case-insensitive system\OS resources.
OrdinalIgnoreCase
Performs a case-insensitive ordinal comparison.
· Case-insensitive identifiers in standards such as XML and HTTP.
· Case-insensitive security-related settings.
· File paths.
· Registry keys and values.
· Environment variables.
· Resource identifiers (for example, display names).
· Command line arguments
CurrentCulture
Performs a case-sensitive comparison using the current culture.
· While working with most user data (and not system\OS data)
· While showing\sorting the system\OS data mentioned above to the user (but not when comparing for equality).
CurrentCultureIgnoreCase
Performs a case-insensitive comparison using the current culture.
InvariantCulture
Performs a case-sensitive comparison using the invariant culture.
Valid in very rare cases – best is to forget these exist.
InvariantCultureIgnoreCase
Performs a case-insensitive comparison using the invariant culture.
Some Examples!
Use Case
StringComparison to use
Reason
Check file name, URL or registry value etc. for equality
These system resources are case-insensitive (at least in .NET\Win32 context).
Sort file name (or any other system resource) to show to the user in the UI
User will want sorting to be in his culture, the way he understands it.
Comparing PropertyName in WPF’s PropertyChangeHandler – a case insensitive data with a const string
The only reason for using Ordinal (over OrdinalIgnoreCase) is that you know the data will not vary in case and Ordinal is faster.
Other notes
Dictionary<string, int> stringDictionary = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);