Web developers wiki ASP.NET Sitecore Sharepoint Kentico by Evident Interactive

Best practice to compare strings

Modified: 2009/11/09 10:34 by k.schepens - Categorized as: ASP.NET, Csharp


Use StringComparison.OrdinalIgnoreCase

There are many ways to compare strings in C#. The most simple one is using the == operator. If you want to compare case-insensitive, however, there is no operator available. Many times case-insensitive string compare is performed by case-lowering or case-uppering the text, like so: text1.ToLower() == text2.ToLower(). Unfortunately, this is not a good practice.

The recommended and fastest way to compare case-insensitive is the StringComparison.OrdinalIgnoreCase method:

text1.Equals(text2, StringComparison.OrdinalIgnoreCase);

OrdinalIgnoreCase is typically(*) 25 times faster than a "ToLower()" compare. Well, at 25.000.000 compares per second on an average PC it may not be a major concern.

Microsoft wrote 15 pages on it, titled New Recommendations for Using Strings in Microsoft .NET 2.0 Read it here if you like: http://msdn.microsoft.com/en-us/library/ms973919.aspx

  • : tested on comparing guid's

 © Evident Interactive BV