Operator overloading and testing for null
Operator overloading in C# is basically writing a public static method, like this:
public
static
bool
operator ==(CustomObject
object1,
CustomObject
object2)
{
return
object1.SomeProperty == object2.SomeProperty;
}
Before you do this, it is necessary to check if both parameters are not null, otherwise you will get a NullReferenceException when doing this:
CustomObject
object1 = GetCustomObject();
if
(object1 == null)
But you cannot do the following because it will simply recurse the evaluation to the same method, and give you a StackOverflowException:
public
static
bool
operator ==(CustomObject
object1,
CustomObject
object2)
{
if (object1 ==
null || object2 ==
null)
{
//...
Instead you can cast your parameters to "object"s before evaluating, which will use the == operator for Object:
if ((object)object1 == null || (object)object2 == null)
Also, if you don't want to repeat the whole bunch again for the != operator, you can simply write this:
public
static
bool
operator !=(CustomObject
object1,
CustomObject
object2)
{
return !(object1 ==
object2);
}