Create Complex Structure with Equals and GetHashCode method : Object « Development « VB.Net






Create Complex Structure with Equals and GetHashCode method

 

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 

   
  








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 your own Equals method
4.Create Equals method based on Equals method from fields
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