Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison - strA.ToLower()==strB.ToLower() or strA.Equals(strB,StringComparisonType)?

As per title, what practise for string comparisons do you use and why?

like image 977
maxp Avatar asked Nov 02 '09 09:11

maxp


1 Answers

You haven't specified a platform, but I'm guessing .NET. I would strongly suggest you use the latter form - because case comparisons aren't as simple as you might expect. (It also avoids creating extra strings, but that's a different matter.)

For example, what do you want your code to do when presented with "mail" and "MAIL" when it's running in Turkey? If you use ToLower it will return false, and likewise if you use CurrentCultureIgnoreCase - but if you use InvariantCultureIgnoreCase it will return true. You need to think about the source of the data and what you're trying achieve with it.

See the recommendations for using strings in MSDN for more information and guidance.

Aside from anything else, I'd say that the latter expresses your intent more effectively. You're not actually interested in the lower case values of the strings - you're interested in equality in a case-insensitive way... which is exactly what the second form expresses.

like image 197
Jon Skeet Avatar answered Sep 20 '22 07:09

Jon Skeet