String comparison

Something not many people know: when you need to compare 2 strings in C#.NET you can use the == operator overload:

if(firstString == secondString)
{
    //...
}

This is case sensitive. But when you need to ignore the case please don’t use this:

if(firstString.ToLower() == secondString.ToLower())
{
    //...
}

or this:

if(firstString.ToLower().Equals(secondString.ToLower()))
{
    //...
}

A Framework provides you with utilities, please use them. They are usually better than your implementation!

Use this:

if (firstString.Equals(secondString, StringComparison.OrdinalIgnoreCase))
{
    //...
}

StringComparison is an enum. So please look at the options :)

One thought on “String comparison

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>