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?
Compare() The VB.NET String Compare function is use to compare two String 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.
The == operator compares whether two object references point to the same object. For example: System.
Referential equality JavaScript provides 3 ways to compare values: The strict equality operator === The loose equality operator == Object.is() function.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With