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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With