Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite recursion when overloading ==

I have a class that I want to overload the == operator for in c#. I already have a .Equals override that works properly. When I tried to use my == operator, it gave me a null reference exception on my object (Person). If I try to check if it is null, it will in turn call the same operator to check it against null and create an infinite loop. This seems like a huge flaw and I can't figure out the right way to do it.

public static bool operator ==(Person person, object obj)
{
    return person == null ? person.Equals(obj) : false;
}

public static bool operator !=(Person person, object obj)
{
    return !(person == obj);
}
like image 692
viper110110 Avatar asked Jan 13 '23 06:01

viper110110


1 Answers

Use (object)person == null to force it to use the == operator of Object (or use ReferenceEquals). See http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx.

like image 102
Ryan M Avatar answered Jan 25 '23 14:01

Ryan M