Infinite recursion on overload ==

I have a class that I want to overload the == operator for C #. I already have a .Equals override that works correctly. When I tried to use my == operator, it gave me a reference exception to my object (Person). If I try to check if it is null, it, in turn, will call the same statement to check it for null and create an infinite loop. This seems like a huge flaw, and I can't figure out how 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); } 
+4
source share
1 answer

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

+8
source

Source: https://habr.com/ru/post/1483444/


All Articles