Overriding == operator. How to compare to null?
you could alway override and put
(Object)(person1)==null
I'd imagine this would work, not sure though.
Easier than any of those approaches would be to just use
public static bool operator ==(Person person1, Person person2)
{
EqualityComparer<Person>.Default.Equals(person1, person2)
}
This has the same null equality semantics as the approaches that everyone else is proposing, but it's the framework's problem to figure out the details :)
I've always done it this way (for the == and != operators) and I reuse this code for every object I create:
public static bool operator ==(Person lhs, Person rhs)
{
// If left hand side is null...
if (System.Object.ReferenceEquals(lhs, null))
{
// ...and right hand side is null...
if (System.Object.ReferenceEquals(rhs, null))
{
//...both are null and are Equal.
return true;
}
// ...right hand side is not null, therefore not Equal.
return false;
}
// Return true if the fields match:
return lhs.Equals(rhs);
}
"!=" then goes like this:
public static bool operator !=(Person lhs, Person rhs)
{
return !(lhs == rhs);
}
Edit
I modified the ==
operator function to match Microsoft's suggested implementation here.
Use object.ReferenceEquals(person1, null)
or the new is operator instead of the ==
operator:
public static bool operator ==(Person person1, Person person2)
{
if (person1 is null)
{
return person2 is null;
}
return person1.Equals(person2);
}