In .NET there are 6 ways to compare strings.  Really? Why is it so difficult?

Ordinal

Performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-sensitive resources such as passwords.

OrdinalIgnoreCase

Treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames.

InvariantCulture

Compares strings in a linguistically relevant manner, but it is not suitable for display in any particular culture. Its major application is to order strings in a way that will be identical across cultures.

InvariantCultureIgnoreCase

Compares strings in a linguistically relevant manner that ignores case, but it is not suitable for display in any particular culture. Its major application is to order strings in a way that will be identical across cultures.

CurrentCulture

Can be used when strings are linguistically relevant. For example, if strings are displayed to the user, or if strings are the result of user interaction, culture-sensitive string comparison should be used to order the string data.

CurrentCultureIgnoreCase

Can be used when strings are linguistically relevant but their case is not. For example, if strings are displayed to the user but case is unimportant, culture-sensitive, case-insensitive string comparison should be used to order the string data.

Tip: You should always specify explicitly the comparer as the default value is not consistent. For instance, string.IndexOf uses the current culture whereas string.Equals uses Ordinal.

i.e.

string.Equals("", "", StringComparison.Ordinal);
new [] { "" }.Contains("", StringComparer.Ordinal);
new Dictionary(StringComparer.Ordinal);

</string,>

Refer to blog for additional samples and Rosyln analyzer to help with coding within your IDE.

Comments


Comments are closed

About Us

Web/Mobile Solutions

Our Contacts

Cincinnati, OH 45069