Best Practice: Comparing Two Reference Type Instances in C#
When comparing reference types, be sure to clarify the expected behavior: value equality or reference identity.
Override the equality operator ("==") and the Equals method to achieve reference identity
In the past, developers would override the "==" and Equals methods to check for referential identity. However, coding standards advise against this as it may lead to ambiguity in certain situations.
Option 1: Implement the IEquatable
For reference types with value semantics (immutable types where equality is treated as equality), the recommended approach is to implement the System.IEquatable
Example:
<code class="language-csharp">class Point : IEquatable<Point> { // ... public bool Equals(Point other) { return X.Equals(other.X) && Y.Equals(other.Y); } // ... }</code>
Option 2: Use a custom Equals method with type checking to achieve value equality
If you prefer a custom Equals method, make sure it checks both reference equality and the type of the object being compared. This prevents unexpected behavior when comparing derived class objects.
Example:
<code class="language-csharp">public bool Equals(Point other) { if (other is null) return false; if (other.GetType() != GetType()) return false; return X.Equals(other.X) && Y.Equals(other.Y); }</code>
When to use referential identity
Do not implement the "==" and "!=" operators for reference classes that do not represent immutable values. Instead, rely on their default behavior of comparing objects for identity.
The above is the detailed content of How Should I Compare Two Instances of a Reference Type in C#?. For more information, please follow other related articles on the PHP Chinese website!