Click here to Skip to main content
15,884,099 members
Articles / Programming Languages / C#

String.Compare vs. CultureInfo.Compare

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
10 Nov 2011LGPL31 min read 10.9K  
An API available in the .NET FCL called CultureInfo.Compare().

A few moments ago I learned something on StackOverflow, and I thought of sharing it with you. For comparing strings that are culture specific, we normally use String.Compare. But very rarely, would people have seen another API available in the .NET FCL called CultureInfo.Compare().

So I started to dig in and saw what is actually the difference between them, in fact they do work the same. Upon looking inside the IL, I came to know that string.Compare in fact does call or use the CultureInfo.Compare() API.

C#
public static int Compare(string strA, string strB, CultureInfo culture, CompareOptions options)
{
  if (culture == null)
  {
    throw new ArgumentNullException("culture");
  }
  return culture.CompareInfo.Compare(strA, strB, options);
}

So following are my observations on this:

  • String.Compare first checks if input is null i.e., the CultureInfo argument.
  • CultureInfo.Compare does not check for null except at a later stage it does check for string arguments but not for CultureInfo.
  • The CultureInfo.Compare API internally calls the String.Compare() API again if OrdinalIgnoreCase is passed for the CompareOptions argument.

So based on the above points, it is best to use the String.Compare API itself, because it first does null checking and the String class is a BCL class. I believe it also avoids confusions for other developers looking at your code if you’re using some alternative, in this case the CultureInfo.Compare API.

That’s all for now, your comments are always welcome.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Software Developer (Senior) Siemens
India India
A .net developer since 4+ years, wild, curious and adventurous nerd.

Loves Trekking/Hiking, animals and nature.

A FOSS/Linux maniac by default Wink | ;)

An MVP aspirant and loves blogging -> https://adventurouszen.wordpress.com/

Comments and Discussions

 
-- There are no messages in this forum --