Safely overload the equality operator (==) to avoid infinite recursion
When overloading the equality operator (==), be sure to handle null cases carefully to prevent infinite recursion. An infinite loop of == checks may result when one or both operands are empty.
To resolve this issue, please use the ReferenceEquals
method instead of == to compare the null value of the object. This method returns true if both operands are null or if both operands refer to the same object, false otherwise. By using ReferenceEquals
, the following code handles null values accurately:
<code class="language-csharp">Foo foo1 = null; Foo foo2 = new Foo(); Assert.IsFalse(foo1 == foo2); public static bool operator ==(Foo foo1, Foo foo2) { if (object.ReferenceEquals(null, foo1)) return object.ReferenceEquals(null, foo2); return foo1.Equals(foo2); }</code>
By taking this approach, the == overloaded method can efficiently compare Foo objects (regardless of whether they are null) without triggering infinite recursion.
The above is the detailed content of How to Avoid Infinite Recursion When Overloading the Equality Operator (==)?. For more information, please follow other related articles on the PHP Chinese website!