Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare objects in VB.NET

Tags:

vb.net

I want to write a function that accepts two objects as parameters and compare only the fields contained within the objects. I do not know what type the objects will be at design time, but the objects passed will be classes used within our application.

Is it possible to compare object's fields without knowing their types at runtime?

like image 355
StevenMcD Avatar asked Nov 21 '08 14:11

StevenMcD


People also ask

Is a function to comparing the objects in VB net?

Compare() The VB.NET String Compare function is use to compare two String Objects.

How do you compare two objects?

Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity. For example, the expression obj1==obj2 tests the identity, not equality.

Can you use == to compare objects?

The == operator compares whether two object references point to the same object. For example: System.

How do you compare object values?

Referential equality JavaScript provides 3 ways to compare values: The strict equality operator === The loose equality operator == Object.is() function.


2 Answers

Yes, it is possible to find the fields, properties, and methods of objects at runtime. You will need to use System.Reflection and find the matching fields, make sure the datatypes are compatible, and then compare the values.

like image 153
Ryan Avatar answered Oct 10 '22 21:10

Ryan


For this at work we have all our data access classes override GetHashCode: eg.

Public Overrides Function GetHashCode() As Integer
    Dim sb As New System.Text.StringBuilder

    sb.Append(_dateOfBirth)
    sb.Append(_notes)
    sb.Append(Name.LastName)
    sb.Append(Name.Preferred)
    sb.Append(Name.Title)
    sb.Append(Name.Forenames)

    Return sb.ToString.GetHashCode()

End Function

Then to compare two objects, you can say

Public Shared Function Compare(ByVal p1 As Person, ByVal p2 As Person) As Boolean

    Return p1.GetHashCode = p2.GetHashCode

End Function

Or more generically:

object1.GetHashCode = object2.GetHashCode
like image 27
Pondidum Avatar answered Oct 10 '22 20:10

Pondidum