02 Aug 2009

When I was doing String comparison, I always use to do it this way:

String s = "Philippe";

if (s.Equals("Philippe"))
{
    //Not relevant
}

For me, it seems the natural way to write that condition. You can read it out loud as “if s is equal to Philippe”.

However, as the String could come as null, I always ended up with something like this:

if (s != null && s.Equals("Philippe"))
{
    //Not relevant
}

This way, the s.Equals wouldn't throw a NullReferenceException in case of s being null. Again, reading it out loud would be: “if s is not null and s is equal to Philippe”.

And what about doing this:

if ("Philippe".Equals(s))
{
    //Not relevant
}

It feels a lot less natural to me, but the benefits are worth it. Only one condition and no risk of NullReferenceException. If s is null, this will simply return false. It would read as “if Philippe is equal to s”, which doesn’t sound too good, but doesn’t hurt code’s readability.

Just a small trick I wanted to share. I figured it out while reading someone else’s code, which is always interesting.



blog comments powered by Disqus