object.Equals handles null values correctly

code 28 March 2008 | 0 Comments

Here’s the source code, as disassembled by Reflector:

public static bool Equals(object objA, object objB)
{
    return ((objA == objB) || (((objA != null) && (objB != null)) && objA.Equals(objB)));
}

It seems that not even Microsoft knows this! I spotted this code, from ASP.NET’s MVC implementation, on Scott Hanselman’s blog:

return (other != null) &&
  (((other._first == null) && (_first == null)) ||
    ((other._first != null) && other._first.Equals(_first))) &&
  (((other._second == null) && (_second == null)) ||
    ((other._second != null) && other._second.Equals(_second)));

This can be rewritten as:

return (other != null) &&
  object.Equals(other._first, _first) &&
  object.Equals(other._second, _second);

Much nicer!

Tagged in , , ,

Leave a Reply