Determines whether the specified object is equal to the current object.
Assembly: mscorlib (in mscorlib.dll)
Public Overridable Function Equals ( _
obj As [%$TOPIC/bsc2ak47_en-us_VS_110_1_0_0_0_0%] _
) As [%$TOPIC/bsc2ak47_en-us_VS_110_1_0_0_0_1%]
public virtual [%$TOPIC/bsc2ak47_en-us_VS_110_1_0_1_0_0%] Equals(
[%$TOPIC/bsc2ak47_en-us_VS_110_1_0_1_0_1%] obj
)
public:
virtual [%$TOPIC/bsc2ak47_en-us_VS_110_1_0_2_0_0%] Equals(
[%$TOPIC/bsc2ak47_en-us_VS_110_1_0_2_0_1%]^ obj
)
abstract Equals :
obj:[%$TOPIC/bsc2ak47_en-us_VS_110_1_0_3_0_0%] -> [%$TOPIC/bsc2ak47_en-us_VS_110_1_0_3_0_1%]
override Equals :
obj:[%$TOPIC/bsc2ak47_en-us_VS_110_1_0_3_0_2%] -> [%$TOPIC/bsc2ak47_en-us_VS_110_1_0_3_0_3%]
Parameters
- obj
- Type:
SystemObject
The object to compare with the current object.
Return Value
Type: SystemBooleantrue if the specified object is equal to the current object; otherwise, false.
The type of comparison between the current instance and the obj parameter depends on whether the current instance is a reference type or a value type. If the current instance is a reference type, the Equals(Object) method tests for reference equality, and a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method. Reference equality means that the object variables that are compared refer to the same object. The following example illustrates the result of such a comparison. It defines a Person class, which is a reference type, and calls the Person class constructor to instantiate two new Person objects, person1a and person2, which have the same value. It also assigns person1a to another object variable, person1b. As the output from the example shows, person1a and person1b are equal because they reference the same object. However, person1a and person2 are not equal, although they have the same value.
' Define a reference type that does not override Equals.
Public Class Person
Private personName As String
Public Sub New(name As String)
Me.personName = name
End Sub
Public Overrides Function ToString() As String
Return Me.personName
End Function
End Class
Module Example
Public Sub Main()
Dim person1a As New Person("John")
Dim person1b As Person = person1a
Dim person2 As New Person(person1a.ToString())
Console.WriteLine("Calling Equals:")
Console.WriteLine("person1a and person1b: {0}", person1a.Equals(person1b))
Console.WriteLine("person1a and person2: {0}", person1a.Equals(person2))
Console.WriteLine()
Console.WriteLine("Casting to an Object and calling Equals:")
Console.WriteLine("person1a and person1b: {0}", CObj(person1a).Equals(CObj(person1b)))
Console.WriteLine("person1a and person2: {0}", CObj(person1a).Equals(CObj(person2)))
End Sub
End Module
' The example displays the following output:
' Calling Equals:
' person1a and person1b: True
' person1a and person2: False
'
' Casting to an Object and calling Equals:
' person1a and person1b: True
' person1a and person2: False
using System;
// Define a reference type that does not override Equals.
public class Person
{
private string personName;
public Person(string name)
{
this.personName = name;
}
public override string ToString()
{
return this.personName;
}
}
public class Example
{
public static void Main()
{
Person person1a = new Person("John");
Person person1b = person1a;
Person person2 = new Person(person1a.ToString());
Console.WriteLine("Calling Equals:");
Console.WriteLine("person1a and person1b: {0}", person1a.Equals(person1b));
Console.WriteLine("person1a and person2: {0}", person1a.Equals(person2));
Console.WriteLine("\nCasting to an Object and calling Equals:");
Console.WriteLine("person1a and person1b: {0}", ((object) person1a).Equals((object) person1b));
Console.WriteLine("person1a and person2: {0}", ((object) person1a).Equals((object) person2));
}
}
// The example displays the following output:
// person1a and person1b: True
// person1a and person2: False
//
// Casting to an Object and calling Equals:
// person1a and person1b: True
// person1a and person2: False
If the current instance is a value type, the Equals(Object) method tests for value equality. Value equality means the following:
The two objects are of the same type. As the following example shows, a Byte object that has a value of 12 does not equal an Int32 object that has a value of 12, because the two objects have different run-time types.
Module Example Public Sub Main() Dim value1 As Byte = 12 Dim value2 As Integer = 12 Dim object1 As Object = value1 Dim object2 As Object = value2 Console.WriteLine("{0} ({1}) = {2} ({3}): {4}", object1, object1.GetType().Name, object2, object2.GetType().Name, object1.Equals(object2)) End Sub End Module ' The example displays the following output: ' 12 (Byte) = 12 (Int32): Falseusing System; public class Example { public static void Main() { byte value1 = 12; int value2 = 12; object object1 = value1; object object2 = value2; Console.WriteLine("{0} ({1}) = {2} ({3}): {4}", object1, object1.GetType().Name, object2, object2.GetType().Name, object1.Equals(object2)); } } // The example displays the following output: // 12 (Byte) = 12 (Int32): FalseThe values of the public and private fields of the two objects are equal. The following example tests for value equality. It defines a Person structure, which is a value type, and calls the Person class constructor to instantiate two new Person objects, person1 and person2, which have the same value. As the output from the example shows, although the two object variables refer to different objects, person1 and person2 are equal because they have the same value for the private personName field.
' Define a value type that does not override Equals. Public Structure Person Private personName As String Public Sub New(name As String) Me.personName = name End Sub Public Overrides Function ToString() As String Return Me.personName End Function End Structure Module Example Public Sub Main() Dim p1 As New Person("John") Dim p2 As New Person("John") Console.WriteLine("Calling Equals:") Console.WriteLine(p1.Equals(p2)) Console.WriteLine() Console.WriteLine("Casting to an Object and calling Equals:") Console.WriteLine(CObj(p1).Equals(p2)) End Sub End Module ' The example displays the following output: ' Calling Equals: ' True ' ' Casting to an Object and calling Equals: ' Trueusing System; // Define a value type that does not override Equals. public struct Person { private string personName; public Person(string name) { this.personName = name; } public override string ToString() { return this.personName; } } public struct Example { public static void Main() { Person person1 = new Person("John"); Person person2 = new Person("John"); Console.WriteLine("Calling Equals:"); Console.WriteLine(person1.Equals(person2)); Console.WriteLine("\nCasting to an Object and calling Equals:"); Console.WriteLine(((object) person1).Equals((object) person2)); } } // The example displays the following output: // Calling Equals: // True // // Casting to an Object and calling Equals: // True
Because the Object class is the base class for all types in the .NET Framework, the ObjectEquals(Object) method provides the default equality comparison for all other types. However, types often override the Equals method to implement value equality. For more information, see the Notes for Callers and Notes for Inheritors sections.
Notes for the Windows Runtime
When you call the Equals(Object) method overload on a class in the Windows Runtime, it provides the default behavior for classes that don’t override Equals(Object). This is part of the support that the .NET Framework provides for the Windows Runtime (see .NET Framework Support for Windows Store Apps and Windows Runtime). Classes in the Windows Runtime don’t inherit Object, and currently don’t implement an Equals(Object) method. However, they appear to have ToString, Equals(Object), and GetHashCode methods when you use them in your C# or Visual Basic code, and the .NET Framework provides the default behavior for these methods.
Note |
|---|
Windows Runtime classes that are written in C# or Visual Basic can override the Equals(Object) method overload. |
Notes for Callers
Derived classes frequently override the ObjectEquals(Object) method to implement value equality. In addition, types also frequently provide an additional strongly typed overload to the Equals method. When you call the Equals method to test for equality, you should know whether the current instance overrides ObjectEquals and understand how a particular call to an Equals method is resolved. Otherwise, you may be performing a test for equality that is different from what you intended, and the method may return an unexpected value.
The following example provides an illustration. It instantiates three StringBuilder objects with identical strings, and then makes four calls to Equals methods. The first method call returns true, and the remaining three return false.
Imports System.Text
Module Example
Public Sub Main()
Dim sb1 As New StringBuilder("building a string...")
Dim sb2 As New StringBuilder("building a string...")
Console.WriteLine("sb1.Equals(sb2): {0}", sb1.Equals(sb2))
Console.WriteLine("CObj(sb1).Equals(sb2): {0}",
CObj(sb1).Equals(sb2))
Console.WriteLine("Object.Equals(sb1, sb2): {0}",
Object.Equals(sb1, sb2))
Console.WriteLine()
Dim sb3 As Object = New StringBuilder("building a string...")
Console.WriteLine("sb3.Equals(sb2): {0}", sb3.Equals(sb2))
End Sub
End Module
' The example displays the following output:
' sb1.Equals(sb2): True
' CObj(sb1).Equals(sb2): False
' Object.Equals(sb1, sb2): False
'
' sb3.Equals(sb2): False
using System;
using System.Text;
public class Example
{
public static void Main()
{
StringBuilder sb1 = new StringBuilder("building a string...");
StringBuilder sb2 = new StringBuilder("building a string...");
Console.WriteLine("sb1.Equals(sb2): {0}", sb1.Equals(sb2));
Console.WriteLine("((Object) sb1).Equals(sb2): {0}",
((Object) sb1).Equals(sb2));
Console.WriteLine("Object.Equals(sb1, sb2): {0}",
Object.Equals(sb1, sb2));
Object sb3 = new StringBuilder("building a string...");
Console.WriteLine("\nsb3.Equals(sb2): {0}", sb3.Equals(sb2));
}
}
// The example displays the following output:
// sb1.Equals(sb2): True
// ((Object) sb1).Equals(sb2): False
// Object.Equals(sb1, sb2): False
//
// sb3.Equals(sb2): False
In the first case, the strongly typed StringBuilderEquals(StringBuilder) method overload, which tests for value equality, is called. Because the strings assigned to the two StringBuilder objects are equal, the method returns true. However, StringBuilder does not override ObjectEquals(Object). Because of this, when the StringBuilder object is cast to an Object, when a StringBuilder instance is assigned to a variable of type Object, and when the ObjectEquals(Object, Object) method is passed two StringBuilder objects, the default ObjectEquals(Object) method is called. Because StringBuilder is a reference type, this is equivalent to passing the two StringBuilder objects to the ReferenceEquals method. Although all three StringBuilder objects contain identical strings, they refer to three distinct objects. As a result, these three method calls return false.
You can compare the current object to another object for reference equality by calling the ReferenceEquals method. In Visual Basic, you can also use the is keyword (for example, If Me Is otherObject Then ...).
Notes for Inheritors
When you define your own type, that type inherits the functionality defined by the Equals method of its base type. The following table lists the default implementation of the Equals method for the major categories of types in the .NET Framework.
Type category | Equality defined by | Comments |
|---|---|---|
Class derived directly from Object | ObjectEquals(Object) | Reference equality; equivalent to calling ObjectReferenceEquals. |
Structure | Value equality; either direct byte-by-byte comparison or field-by-field comparison using reflection. | |
Enumeration | Values must have the same enumeration type and the same underlying value. | |
Delegate | Delegates must have the same type with identical invocation lists. | |
Interface | ObjectEquals(Object) | Reference equality. |
You can also override the default implementation of Equals to test for value equality instead of reference equality and to define the precise meaning of value equality. Such implementations of Equals return true if the two objects have the same value, even if they are not the same instance. The type's implementer decides what constitutes an object's value, but it is typically some or all the data stored in the instance variables of the object. For example, the value of a String object is based on the characters of the string; the StringEquals(Object) method overrides the ObjectEquals(Object) method to return true for any two string instances that contain the same characters in the same order.
The following example shows how to override the ObjectEquals(Object) method to test for value equality. It overrides the Equals method for the Person class. If Person accepted its base class implementation of equality, two Person objects would be equal only if they referenced a single object. However, in this case, two Person objects are equal if they have the same value for the Person.Id property.
Public Class Person
Private idNumber As String
Private personName As String
Public Sub New(name As String, id As String)
Me.personName = name
Me.idNumber = id
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
Dim personObj As Person = TryCast(obj, Person)
If personObj Is Nothing Then
Return False
Else
Return idNumber.Equals(personObj.idNumber)
End If
End Function
Public Overrides Function GetHashCode() As Integer
Return Me.idNumber.GetHashCode()
End Function
End Class
Module Example
Public Sub Main()
Dim p1 As New Person("John", "63412895")
Dim p2 As New Person("Jack", "63412895")
Console.WriteLine(p1.Equals(p2))
Console.WriteLine(Object.Equals(p1, p2))
End Sub
End Module
' The example displays the following output:
' True
' True
public class Person
{
private string idNumber;
private string personName;
public Person(string name, string id)
{
this.personName = name;
this.idNumber = id;
}
public override bool Equals(Object obj)
{
Person personObj = obj as Person;
if (personObj == null)
return false;
else
return idNumber.Equals(personObj.idNumber);
}
public override int GetHashCode()
{
return this.idNumber.GetHashCode();
}
}
public class Example
{
public static void Main()
{
Person p1 = new Person("John", "63412895");
Person p2 = new Person("Jack", "63412895");
Console.WriteLine(p1.Equals(p2));
Console.WriteLine(Object.Equals(p1, p2));
}
}
// The example displays the following output:
// True
// True
The following statements must be true for all implementations of the Equals(Object) method. In the list, x, y, and z represent object references that are not null.
x.Equals(x) returns true, except in cases that involve floating-point types. See ISO/IEC/IEEE 60559:2011, Information technology -- Microprocessor Systems -- Floating-Point arithmetic.
x.Equals(y) returns the same value as y.Equals(x).
x.Equals(y) returns true if both x and y are NaN.
If (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true.
Successive calls to x.Equals(y) return the same value as long as the objects referenced by x and y are not modified.
x.Equals(null) returns false.
Implementations of Equals must not throw exceptions.
Follow these guidelines when overriding Equals(Object):
Types that implement IComparable must override Equals(Object).
Types that override Equals(Object) must also override GetHashCode; otherwise, hash tables might not work correctly.
If your programming language supports operator overloading and you overload the equality operator for a given type, you must also override the Equals(Object) method to return the same result as the equality operator. This helps ensure that class library code that uses Equals (such as ArrayList and Hashtable) behaves in a manner that is consistent with the way the equality operator is used by application code.
The following guidelines apply to overriding Equals(Object) for a reference type:
Consider overriding Equals if the semantics of the type are based on the fact that the type represents some value(s).
Most reference types must not overload the equality operator, even if they override Equals. However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you must override the equality operator.
The following guidelines apply to overriding Equals(Object) for a value type:
If you are defining a value type that includes one or more fields whose values are reference types, you should override Equals(Object). The Equals(Object) implementation provided by ValueType performs a byte-by-byte comparison for value types whose fields are all value types, but it uses reflection to perform a field-by-field comparison of value types whose fields include reference types.
If you override Equals and your development language supports operator overloading, you must overload the equality operator.
The following example shows a Point class that overrides the Equals method to provide value equality, and a Point3D class that is derived from Point. Because Point overrides ObjectEquals(Object) to test for value equality, the ObjectEquals(Object) method is not called. However, Point3D.Equals calls Point.Equals because Point implements ObjectEquals(Object) in a manner that provides value equality.
Class Point
Protected x, y As Integer
Public Sub New()
Me.x = 0
Me.y = 0
End Sub
Public Sub New(ByVal X As Integer, ByVal Y As Integer)
Me.x = X
Me.y = Y
End Sub
Public Overrides Function Equals(obj As Object) As Boolean
' Check for null and compare run-time types.
If obj Is Nothing OrElse Not Me.GetType().Equals(obj.GetType()) Then
Return False
Else
Dim p As Point = DirectCast(obj, Point)
Return x = p.x AndAlso y = p.y
End If
End Function
Public Overrides Function GetHashCode() As Integer
Return x ^ y
End Function
End Class
Class Point3D : Inherits Point
Private z As Integer
Public Sub New(ByVal X As Integer, ByVal Y As Integer, ByVal Z As Integer)
Me.x = X
Me.y = Y
Me.z = Z
End Sub
Public Overrides Function Equals(ByVal obj As Object) As Boolean
Return MyBase.Equals(obj)
'Return MyBase.Equals(obj) AndAlso z = CType(obj, Point3D).z
End Function
Public Overrides Function GetHashCode() As Integer
Return MyBase.GetHashCode() ^ z
End Function
End Class
Module Example
Public Sub Main()
Dim point2D As New Point(5, 5)
Dim point3Da As New Point3D(5, 5, 2)
Dim point3Db As New Point3D(5, 5, 2)
If Not point2D.Equals(point3Da) Then
Console.WriteLine("point2D does not equal point3Da")
End If
If Not point3Db.Equals(point2D) Then
Console.WriteLine("point3Db does not equal point2D")
End If
If point3Da.Equals(point3Db) Then
Console.WriteLine("point3Da equals point3Db")
End If
End Sub
End Module
' The example displays the following output
' point2D does not equal point3Da
' point3Db does not equal point2D
' point3Da equals point3Db
using System;
class Point
{
protected int x, y;
public Point() {
this.x = 0;
this.y = 0;
}
public Point(int X, int Y) {
this.x = X;
this.y = Y;
}
public override bool Equals(Object obj) {
//Check for null and compare run-time types.
if (obj == null || this.GetType() != obj.GetType()) {
return false;
}
else {
Point p = (Point) obj;
return (x == p.x) && (y == p.y);
}
}
public override int GetHashCode() {
return x ^ y;
}
}
class Point3D: Point
{
int z;
public Point3D(int X, int Y, int Z) {
this.x = X;
this.y = Y;
this.z = Z;
}
public override bool Equals(Object obj) {
return base.Equals(obj) && z == ((Point3D)obj).z;
}
public override int GetHashCode() {
return base.GetHashCode() ^ z;
}
}
class Example
{
public static void Main()
{
Point point2D = new Point(5, 5);
Point3D point3Da = new Point3D(5, 5, 2);
Point3D point3Db = new Point3D(5, 5, 2);
if (!point2D.Equals(point3Da)) {
Console.WriteLine("point2D does not equal point3Da");
}
if (!point3Db.Equals(point2D)) {
Console.WriteLine("point3Db does not equal point2D");
}
if (point3Da.Equals(point3Db)) {
Console.WriteLine("point3Da equals point3Db");
}
}
}
// The example displays the following output:
// point2D does not equal point3Da
// point3Db does not equal point2D
// point3Da equals point3Db
using namespace System;
ref class Point: public Object
{
protected:
int x;
int y;
public:
Point()
{
this->x = 0;
this->y = 0;
}
Point( int X, int Y )
{
this->x = X;
this->y = Y;
}
virtual bool Equals( Object^ obj ) override
{
//Check for null and compare run-time types.
if ( obj == nullptr || GetType() != obj->GetType() )
return false;
Point ^ p = dynamic_cast<Point^>(obj);
return (x == p->x) && (y == p->y);
}
virtual int GetHashCode() override
{
return x ^ y;
}
};
ref class Point3D: public Point
{
private:
int z;
public:
Point3D( int X, int Y, int Z )
{
this->x = X;
this->y = Y;
this->z = Z;
}
virtual bool Equals( Object^ obj ) override
{
return Point::Equals( obj ) && z == (dynamic_cast<Point3D^>(obj))->z;
}
virtual int GetHashCode() override
{
return Point::GetHashCode() ^ z;
}
};
The Point.Equals method checks to make sure that the obj argument is not null and that it references an instance of the same type as this object. If either check fails, the method returns false.
The Point.Equals method calls the GetType method to determine whether the run-time types of the two objects are identical. If the method used a check of the form obj is Point in C# or TryCast(obj, Point) in Visual Basic, the check would return true in cases where obj is an instance of a derived class of Point, even though obj and the current instance are not of the same run-time type. Having verified that both objects are of the same type, the method casts obj to type Point and returns the result of comparing the instance variables of the two objects.
In Point3D.Equals, the inherited Point.Equals method, which overrides ObjectEquals(Object), is invoked before anything else is done. The inherited Point.Equals method checks to make sure that obj is not null, that obj is an instance of the same class as this object, and that the inherited instance variables match. Only when the inherited Point.Equals method returns true does the method compare the instance variables introduced in the derived class. Specifically, the cast to Point3D is not executed unless obj has been determined to be of type Point3D or a derived class of Point3D.
The following example defines a Rectangle class that internally implements a rectangle as two Point objects. The Rectangle class also overrides ObjectEquals(Object) to provide for value equality.
Class Rectangle
Private a, b As Point
Public Sub New(ByVal upLeftX As Integer, ByVal upLeftY As Integer, _
ByVal downRightX As Integer, ByVal downRightY As Integer)
Me.a = New Point(upLeftX, upLeftY)
Me.b = New Point(downRightX, downRightY)
End Sub 'New
Public Overrides Function Equals(ByVal obj As [Object]) As Boolean
' Performs an equality check on two rectangles (Point object pairs).
If obj Is Nothing OrElse Not [GetType]().Equals(obj.GetType()) Then
Return False
End If
Dim r As Rectangle = CType(obj, Rectangle)
'Uses Equals to compare variables.
Return a.Equals(r.a) AndAlso b.Equals(r.b)
End Function
Public Overrides Function GetHashCode() As Integer
Return a.GetHashCode() ^ b.GetHashCode()
End Function
End Class
Class Point
Private x As Integer
Private y As Integer
Public Sub New(ByVal X As Integer, ByVal Y As Integer)
Me.x = X
Me.y = Y
End Sub
Public Overrides Function Equals(ByVal obj As [Object]) As Boolean
' Performs an equality check on two points (integer pairs).
If obj Is Nothing OrElse Not [GetType]().Equals(obj.GetType()) Then
Return False
End If
Dim p As Point = CType(obj, Point)
Return x = p.x AndAlso y = p.y
End Function
Public Overrides Function GetHashCode() As Integer
Return x.GetHashCode() ^ y.GetHashCode()
End Function
End Class
Class Example
Public Shared Sub Main()
Dim r1 As New Rectangle(0, 0, 100, 200)
Dim r2 As New Rectangle(0, 0, 100, 200)
Dim r3 As New Rectangle(0, 0, 150, 200)
If r1.Equals(r2) Then
Console.WriteLine("Rectangle r1 equals rectangle r2!")
End If
If Not r2.Equals(r3) Then
Console.WriteLine("But rectangle r2 does not equal rectangle r3.")
End If
End Sub
End Class
' The example displays the following output:
' Rectangle r1 equals rectangle r2!
' But rectangle r2 does not equal rectangle r3.
using System;
class Rectangle
{
Point a, b;
public Rectangle(int upLeftX, int upLeftY, int downRightX, int downRightY) {
this.a = new Point(upLeftX, upLeftY);
this.b = new Point(downRightX, downRightY);
}
public override bool Equals(Object obj) {
// Performs an equality check on two rectangles (Point object pairs).
if (obj == null || GetType() != obj.GetType())
return false;
Rectangle r = (Rectangle)obj;
//Uses Equals to compare variables.
return a.Equals(r.a) && b.Equals(r.b);
}
public override int GetHashCode() {
return a.GetHashCode() ^ b.GetHashCode();
}
}
class Point
{
private int x;
private int y;
public Point(int X, int Y) {
this.x = X;
this.y = Y;
}
public override bool Equals (Object obj) {
// Performs an equality check on two points (integer pairs).
if (obj == null || GetType() != obj.GetType()) return false;
Point p = (Point)obj;
return (x == p.x) && (y == p.y);
}
public override int GetHashCode() {
return x.GetHashCode() ^ y.GetHashCode();
}
}
class Example
{
public static void Main()
{
Rectangle r1 = new Rectangle(0, 0, 100, 200);
Rectangle r2 = new Rectangle(0, 0, 100, 200);
Rectangle r3 = new Rectangle(0, 0, 150, 200);
if (r1.Equals(r2)) {
Console.WriteLine("Rectangle r1 equals rectangle r2!");
}
if (!r2.Equals(r3)) {
Console.WriteLine("But rectangle r2 does not equal rectangle r3.");
}
}
}
// The example displays the following output:
// Rectangle r1 equals rectangle r2!
// But rectangle r2 does not equal rectangle r3.
ref class Rectangle
{
private:
Point^ a;
Point^ b;
public:
Rectangle( int upLeftX, int upLeftY, int downRightX, int downRightY )
{
this->a = gcnew Point( upLeftX,upLeftY );
this->b = gcnew Point( downRightX,downRightY );
}
virtual bool Equals( Object^ obj ) override
{
// Performs an equality check on two rectangles (Point object pairs).
if ( obj == nullptr || GetType() != obj->GetType() )
return false;
Rectangle^ r = dynamic_cast<Rectangle^>(obj);
//Uses Equals to compare variables.
return a->Equals( r->a ) && b->Equals( r->b );
}
virtual int GetHashCode() override
{
return a->GetHashCode() ^ b->GetHashCode();
}
};
Some languages such as C# and Visual Basic support operator overloading. When a type overloads the equality operator, it must also override the Equals(Object) method to provide the same functionality. This is typically accomplished by writing the Equals(Object) method in terms of the overloaded equality operator, as in the following example.
Public Structure Complex
Public re, im As Double
Public Overrides Function Equals(ByVal obj As [Object]) As Boolean
Return TypeOf obj Is Complex AndAlso Me = CType(obj, Complex)
End Function
Public Overrides Function GetHashCode() As Integer
Return re.GetHashCode() ^ im.GetHashCode()
End Function
Public Shared Operator = (x As Complex, y As Complex) As Boolean
Return x.re = y.re AndAlso x.im = y.im
End Operator
Public Shared Operator <> (x As Complex, y As Complex) As Boolean
Return Not (x = y)
End Operator
End Structure
Class Example
Public Shared Sub Main()
Dim cmplx1, cmplx2 As Complex
cmplx1.re = 4.0
cmplx1.im = 1.0
cmplx2.re = 2.0
cmplx2.im = 1.0
If cmplx1 <> cmplx2 Then
Console.WriteLine("The two objects are not equal.")
End If
If Not cmplx1.Equals(cmplx2) Then
Console.WriteLine("The two objects are not equal.")
End If
cmplx2.re = 4.0
If cmplx1.Equals(cmplx2) Then
Console.WriteLine("The two objects are now equal!")
End If
If cmplx1 = cmplx2 Then
Console.WriteLine("The two objects are now equal!")
End If
End Sub
End Class
' The example displays the following output:
' The two objects are not equal.
' The two objects are not equal.
' The two objects are now equal!
' The two objects are now equal!
using System;
public struct Complex {
public double re, im;
public override bool Equals(Object obj) {
return obj is Complex && this == (Complex)obj;
}
public override int GetHashCode() {
return re.GetHashCode() ^ im.GetHashCode();
}
public static bool operator ==(Complex x, Complex y) {
return x.re == y.re && x.im == y.im;
}
public static bool operator !=(Complex x, Complex y) {
return !(x == y);
}
}
class MyClass {
public static void Main() {
Complex cmplx1, cmplx2;
cmplx1.re = 4.0;
cmplx1.im = 1.0;
cmplx2.re = 2.0;
cmplx2.im = 1.0;
if (cmplx1 != cmplx2)
Console.WriteLine("The two objects are not equal.");
if (! cmplx1.Equals(cmplx2))
Console.WriteLine("The two objects are not equal.");
cmplx2.re = 4.0;
if (cmplx1 == cmplx2)
Console.WriteLine("The two objects are now equal!");
if (cmplx1.Equals(cmplx2))
Console.WriteLine("The two objects are now equal!");
}
}
// The example displays the following output:
// The two objects are not equal.
// The two objects are not equal.
// The two objects are now equal!
// The two objects are now equal!
using namespace System;
public value struct Complex
{
public:
double re;
double im;
virtual bool Equals( Object^ obj ) override
{
return (dynamic_cast<Complex^>(obj) != nullptr) && (*this == *dynamic_cast<Complex^>(obj));
}
virtual int GetHashCode() override
{
return re.GetHashCode() ^ im.GetHashCode();
}
static bool operator==( Complex x, Complex y )
{
return x.re == y.re && x.im == y.im;
}
static bool operator!=( Complex x, Complex y )
{
return !(x == y);
}
};
int main()
{
Complex cmplx1;
Complex cmplx2;
cmplx1.re = 4.0;
cmplx1.im = 1.0;
cmplx2.re = 2.0;
cmplx2.im = 1.0;
if (cmplx1 != cmplx2)
Console::WriteLine( "The two objects are not equal." );
if (!(cmplx1.Equals(cmplx2)))
Console::WriteLine( "The two objects are not equal." );
cmplx2.re = 4.0;
if (cmplx1 == cmplx2 )
Console::WriteLine( "The two objects are now equal!" );
if (cmplx1.Equals(cmplx2))
Console::WriteLine( "The two objects are now equal!" );
}
// The example displays the following output:
// The two objects are not equal.
// The two objects are not equal.
// The two objects are now equal!
// The two objects are now equal!
Because Complex is a value type, it cannot be derived from. Therefore, the override to Equals(Object) method need not call GetType to determine the precise run-time type of each object, but can instead use the is operator in C# or the TypeOf operator in Visual Basic to check the type of the obj parameter.
Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Note