Create your own Equals method : Object « Development « VB.Net






Create your own Equals method

 
Imports System

Class Point
    Inherits Object
    Protected x, y As Integer
    Public Sub New() 
        Me.x = 0
        Me.y = 0
    End Sub 'New

    Public Sub New(ByVal X As Integer, ByVal Y As Integer) 
        Me.x = X
        Me.y = Y
    End Sub 'New

    Public Overrides Function Equals(ByVal obj As Object) As Boolean 
        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 'Equals

    Public Overrides Function GetHashCode() As Integer 
        Return x ^ y
    End Function 'GetHashCode
End Class 'Point
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 'New

    Public Overrides Function Equals(ByVal obj As Object) As Boolean 
        Return MyBase.Equals(obj) AndAlso z = CType(obj, Point3D).z
    End Function 'Equals

    Public Overrides Function GetHashCode() As Integer 
        Return MyBase.GetHashCode() ^ z
    End Function 'GetHashCode
End Class 'Point3D

Class [MyClass]
    Public Shared 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("Likewise, point3Db does not equal point2D.")
        End If
        If point3Da.Equals(point3Db) Then
            Console.WriteLine("However, point3Da equals point3Db.")
        End If

    End Sub 'Main 
End Class '[MyClass]

   
  








Related examples in the same category

1.Object Class Supports all classes in the .NET Framework class hierarchy
2.Object.Equals Method tells whether the specified Object is equal to the current Object.
3.Create Equals method based on Equals method from fields
4.Create Complex Structure with Equals and GetHashCode method
5.Object.GetType Method Gets the Type of the current instance.
6.Object.MemberwiseClone Method Creates a shallow copy of the current Object.
7.Object Class Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes.
8.Object.GetType Method Gets the Type of the current instance.
9.Object.MemberwiseClone Method Creates a shallow copy of the current Object.
10.Object Class Supports all classes in the .NET Framework class hierarchy
11.Object.GetType Method Gets the Type of the current instance.
12.Object.MemberwiseClone Creates a shallow copy of the current Object.
13.No implementation. All members are inherited from Object
14.Overrides ToString function