Export (0) Print
Expand All
Expand Minimize
This topic has not yet been rated - Rate this topic

CA1046: Do not overload operator equals on reference types

TypeName

DoNotOverloadOperatorEqualsOnReferenceTypes

CheckId

CA1046

Category

Microsoft.Design

Breaking Change

Breaking

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

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.

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

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.

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.

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
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.