CA1046: Do not overload operator equals on reference types

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Item Value
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 Suppress Warnings

It is safe to suppress 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 suppress 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);
      }
   }
}

Example

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.

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

CA1013: Overload operator equals on overloading add and subtract

See Also

System.Object.Equals Equality Operators