How to avoid infinite recursion when dealing with null values in operator overloading?
When defining overloads of comparison operators, it is crucial to handle null cases correctly to avoid infinite recursion. The following code demonstrates the infinite recursion problem in overloading of the == operator:
<code class="language-c#">Foo foo1 = null; Foo foo2 = new Foo(); Assert.IsFalse(foo1 == foo2); public static bool operator ==(Foo foo1, Foo foo2) { if (foo1 == null) return foo2 == null; return foo1.Equals(foo2); }</code>
In this scenario, the == operator overload calls itself recursively when one of its operands is empty. To avoid this problem, you need to explicitly check for null values using the ReferenceEquals
method:
<code class="language-c#">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 using ReferenceEquals
, the overload checks whether both operands are empty before proceeding with the equality comparison. This prevents infinite recursion and ensures correct behavior in the null case.
The above is the detailed content of How to Prevent Infinite Recursion in Operator Overloading When Handling Nulls?. For more information, please follow other related articles on the PHP Chinese website!