Mega Code Archive

 
Categories / VB.Net / Development
 

Create Equals method based on Equals method from fields

Imports System 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          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 'Equals     Public Overrides Function GetHashCode() As Integer          Return a.GetHashCode() ^ b.GetHashCode()     End Function 'GetHashCode End Class 'Rectangle 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 '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.GetHashCode() ^ y.GetHashCode()     End Function 'GetHashCode End Class 'Point  Class [MyClass]     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 'Main End Class