Click here to Skip to main content
11,703,632 members (70,667 online)
Click here to Skip to main content

String.Compare vs. CultureInfo.Compare

, 10 Nov 2011 LGPL3 7K
Rate this:
Please Sign up or sign in to vote.
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.

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)

Share

About the Author

zenwalker1985
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/

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150819.1 | Last Updated 10 Nov 2011
Article Copyright 2011 by zenwalker1985
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid