As per title, what practise for string comparisons do you use and why?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
ToLowerit will return false, and likewise if you useCurrentCultureIgnoreCase– but if you useInvariantCultureIgnoreCaseit 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.