Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/fundamentals/code-analysis/quality-rules/ca2224.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ f1_keywords:
helpviewer_keywords:
- "OverrideEqualsOnOverloadingOperatorEquals"
- "CA2224"
dev_langs:
- CSharp
- VB
---
# CA2224: Override Equals on overloading operator equals

Expand Down Expand Up @@ -62,10 +65,14 @@ For more information, see [How to suppress code analysis warnings](../suppress-w

The following example shows a class (reference type) that violates this rule.

:::code language="csharp" source="snippets/csharp/all-rules/ca2224.cs" id="snippet1":::

:::code language="vb" source="snippets/vb/all-rules/ca2224.vb" id="1":::

The following example fixes the violation by overriding <xref:System.Object.Equals%2A?displayProperty=fullName>.

:::code language="csharp" source="snippets/csharp/all-rules/ca2224.cs" id="snippet2":::

:::code language="vb" source="snippets/vb/all-rules/ca2224.vb" id="2":::

## Related rules
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
using System;

namespace ca2224
{
//<snippet1>
// This class violates the rule.
public class Point
{
public int X { get; set; }
public int Y { get; set; }

public Point(int x, int y)
{
X = x;
Y = y;
}

public override int GetHashCode()
{
return HashCode.Combine(X, Y);
}

public static bool operator ==(Point pt1, Point pt2)
{
if (ReferenceEquals(pt1, null) || ReferenceEquals(pt2, null))
return false;

if (pt1.GetType() != pt2.GetType())
return false;

return pt1.X == pt2.X && pt1.Y == pt2.Y;
}

public static bool operator !=(Point pt1, Point pt2)
{
return !(pt1 == pt2);
}
}
//</snippet1>
}

namespace ca2224_2
{
//<snippet2>
// This class satisfies the rule.
public class Point
{
public int X { get; set; }
public int Y { get; set; }

public Point(int x, int y)
{
X = x;
Y = y;
}

public override int GetHashCode()
{
return HashCode.Combine(X, Y);
}

public override bool Equals(object? obj)
{
if (obj is null)
return false;

if (GetType() != obj.GetType())
return false;

Point pt = (Point)obj;
return X == pt.X && Y == pt.Y;
}

public static bool operator ==(Point? pt1, Point? pt2)
{
// Object.Equals calls Point.Equals(Object).
return Equals(pt1, pt2);
}

public static bool operator !=(Point? pt1, Point? pt2)
{
// Object.Equals calls Point.Equals(Object).
return !Equals(pt1, pt2);
}
}
//</snippet2>
}