Share via


CA2231: Overload operator equals on overriding ValueType.Equals

TypeName

OverloadOperatorEqualsOnOverridingValueTypeEquals

CheckId

CA2231

Category

Microsoft.Usage

Breaking Change

Non Breaking

Cause

A value type overrides Object.Equals but does not implement the equality operator.

Rule Description

In most programming languages there is no default implementation of the equality operator (==) for value types. If your programming language supports operator overloads, you should consider implementing the equality operator. Its behavior should be identical to that of Equals.

You cannot use the default equality operator in an overloaded implementation of the equality operator. Doing so will cause a stack overflow. To implement the equality operator, use the Object.Equals method in your implementation. For example:

If (Object.ReferenceEquals(left, Nothing)) Then
    Return Object.ReferenceEquals(right, Nothing)
Else
    Return left.Equals(right)
End If
if (Object.ReferenceEquals(left, null)) 
    return Object.ReferenceEquals(right, null);
return left.Equals(right);

How to Fix Violations

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

When to Suppress Warnings

It is safe to suppress a warning from this rule; however, we recommend that you provide the equality operator if possible.

Example

The following example defines a type that violates this rule.

using System;

namespace UsageLibrary
{
    public struct PointWithoutHash
    {
        private int x,y;

        public PointWithoutHash(int x, int y)
        {
            this.x = x;
            this.y = y;
        }

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

        public int X {get {return x;}}

        public int Y {get {return x;}}

        // Violates rule: OverrideGetHashCodeOnOverridingEquals. 
        // Violates rule: OverrideOperatorEqualsOnOverridingValueTypeEquals. 
        public override bool Equals (object obj)
        {
            if (obj.GetType() != typeof(PointWithoutHash))
                return false;

            PointWithoutHash p = (PointWithoutHash)obj;   
            return ((this.x == p.x) && (this.y == p.y));
        }

    }

}

CA1046: Do not overload operator equals on reference types

CA2225: Operator overloads have named alternates

CA2226: Operators should have symmetrical overloads

CA2224: Override equals on overloading operator equals

CA2218: Override GetHashCode on overriding Equals

See Also

Reference

Object.Equals