String comparison mistakes in C#

I have seen lots of questions on Stack Overflow where String.Compare  is used to compare strings if one needs case insensitive comparison. I have even seen production code using the same method.  I guess the usage is due to most of the developers having c/c++ background and used to methods like strcmpi. 

Code like:

string str1 = "TEST";
string str2 = "test";
bool caseInsensitiveEqual = String.Compare(str1, str2, StringComparison.InvariantCultureIgnoreCase) == 0;

is often found and considered a usual practice when it comes to case insensitive string comparison.

Another way is converting both of the parameters to either upper or lower case and then doing the comparison like:

string str1 = "TEST";
string str2 = "test";
bool caseInsensitiveEqual = str1.ToUpper() == str2.ToUpper();

Both of these approaches would work for most of the time, but there are issues:

  • String.Compare  is used for determining position in sort order (which string is bigger than other)
  • Using ToUpper or ToLower could case incorrect results for strings in different cultures. (The Turkish İ Problem and Why You Should Care)

Solution:

Use the framework provided String.Equals group of methods.

string str1 = "TEST";
string str2 = "test";
bool caseInsensitiveEqual = String.Equals(str1, str2, StringComparison.InvariantCultureIgnoreCase);

It has overloads to specify string comparison approaches using StringComparison Enumeration

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s