简体   繁体   中英

How to check both the objects are same in Vb.net

I am trying to compare to two objects of same type and determine they identical. I have

objA IS objB

also

objA.Equals(objB)

but every time I am getting false . Here is the code I am trying

Public Class RowsDetails    
  Property RelatedEmployee As String = String.Empty
    Property RelatedNumberAs String = String.Empty
    Property Type As String = String.Empty
    Property ReportType As String = String.Empty
    Property status As String = String.Empty
    Property Term As String = String.Empty
    Property Currency As String = String.Empty    

End Class

All the properties have same values in objA and objB. I have gone over some of the articles that explained about implementing IEquatable(of T) .

But they mostly looked like custom logic. I was wondering is there a simple way to do this ?

Thanks In advance.

Any time you compare two Objects a method for determining equivalence must be established.

there are 3 main forms of equivalence:

Type equivalence: done with the TypeOf operator. who's behavior can be found here

Reference equivalence: done with the is operator. found here

Value Equality (which seems to be what your trying to do) requires that a comparement method is defined. Other wise it will take its best guess at doing so, by using the default Equals() method.


If none of these work for you then you HAVE to define your own method of comparing.

the only other way of doing so, other than implementing IEquatable() or overloading Equals(), would be taking a hash of both objects and comparing those.

Object.Equals(Object) is what is called when you call objA.Equals(objB) . What is compared is, are they pointing to the same object.

Dim objA as New RowDetails()
Dim objB = objA

Now they are both pointing to the same object. So...

objA.Equals(objB)

returns True But using the New keyword on both will create 2 different references so they will not be equal with the default implementation of .Equals

Add something like the following to you RowDetails class.

Public Overrides Function Equals(obj As Object) As Boolean
        Dim rowDet As RowsDetails = TryCast(obj, RowsDetails)
        If rowDet Is Nothing Then
            Return False
            'The AndAlso will short circuit as soon as it finds a false
        ElseIf RelatedEmployee = rowDet.RelatedEmployee AndAlso RelatedNumber = rowDet.RelatedNumber AndAlso Type = rowDet.Type Then 'and the rest of the properties
            Return True
        End If
        Return False
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM