.NET Tips and Tricks

Blog archive

Comparing Strings Without Worrying About Case

Developers frequently want to ensure two strings are identical without having to worry if some characters are in uppercase in one string and the same characters are in lowercase in the other string. Frequently, you see developers using either ToUpper or ToLower to avoid the problem:

If Name.ToUpper = OtherName.ToUpper Then...

But both ToUpper and ToLower create new strings, which is extra (and unnecessary) work.

If you can live with some extra typing, you can avoid generating those new strings by using the Equals method that every variable has, passing the InvariantCultureIgnoreCase choice from the StringComparison enumeration:

if (Name.Equals(OtherName, StringComparison.InvariantCultureIgnoreCase))

Now you have much less to worry about.

Posted by Peter Vogel on 08/12/2015


comments powered by Disqus

Featured

Subscribe on YouTube