views:

155

answers:

4

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

A: 

The first seems more natural to me - using the == operator makes more sense than calling a function with a ComparisonType, I think.

warren
+8  A: 

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.

Jon Skeet
A: 

I feel more better in using second one than first one. Because, the second type will be supported in all languages and it will be more convenient to use.

Nila
+2  A: 

The Equals call scales better, as it's one string operation instead of three.

You get the best performance for case insensetive comparison with the StringComparison.OrdinalIgnoreCase option. However, as it doesn't consider cultural differences it might not always give the result that you want.

If you want to change the case for comparison, it's recommended that you use ToUpper rather than ToLower. Some exotic letters doesn't convert properly from upper to lower case, but conversion from lower to upper case works.

In most cases the performance is not crucial, so you should use the alternative that makes most sense in the situation.

You haven't specified which language you are using, but from the == operator it looks like C#. If you would use VB, you should consider that the = operator doesn't use the equality opreator of the string class, but VB's own logic for doing comparisons, which is slightly different.

Guffa