Do not overload operator equals on reference types

TypeName

DoNotOverloadOperatorEqualsOnReferenceTypes

CheckId

CA1046

Category

Microsoft.Design

Breaking Change

Breaking

Cause

A public or nested public reference type overloads the equality operator.

Rule Description

For reference types, the default implementation of the equality operator is almost always correct. By default, two references are equal only if they point to the same object.

How to Fix Violations

To fix a violation of this rule, remove the implementation of the equality operator.

When to Exclude Warnings

It is safe to exclude a warning from this rule when the reference type behaves like a built-in value type. If it is meaningful to do addition or subtraction on instances of the type, it is probably correct to implement the equality operator and exclude the violation.

Example

The following example demonstrates the default behavior when comparing two references.

using System;

namespace DesignLibrary
{
   public class MyReferenceType
   {
      private int a, b;
      public MyReferenceType (int a, int b)
      {
         this.a = a;
         this.b = b;
      }

      public override string ToString()
      {
         return String.Format("({0},{1})", a, b);
      }
   }
}

The following application compares some references.

using System;

namespace DesignLibrary
{
    public class ReferenceTypeEquality
    {
       public static void Main()
       {
          MyReferenceType a = new MyReferenceType(2,2);
          MyReferenceType b = new MyReferenceType(2,2);
          MyReferenceType c = a;
         
          Console.WriteLine("a = new {0} and b = new {1} are equal? {2}", a,b, a.Equals(b)? "Yes":"No");
          Console.WriteLine("c and a are equal? {0}", c.Equals(a)? "Yes":"No");
          Console.WriteLine("b and a are == ? {0}", b == a ? "Yes":"No");
          Console.WriteLine("c and a are == ? {0}", c == a ? "Yes":"No");     
       }
    }
}

This example produces the following output.

Output

a = new (2,2) and b = new (2,2) are equal? No
c and a are equal? Yes
b and a are == ? No
c and a are == ? Yes

Override operator equals on overloading add and subtract

See Also

Reference

Guidelines for Implementing Equals and the Equality Operator (==)
System.Object.Equals