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.