tags:

views:

2287

answers:

4

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.

Thanks

+4  A: 

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.

Ryan
System.Reflection was the namespace I couldn't remember earlier! Thanks a million man!
FailBoy
+1  A: 

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
Pondidum
Nice approach. You could use reflection but this is pretty simple and clean. One thing I would add would be to implement IComparable on your classes as well.
whatknott
Thanks for the idea but I need to be able to compare specific fields but this will be useful somewhere else in our app. Thanks again!
FailBoy
+1  A: 

Hi,

if you do not want to write the Reflection code here is a library which includes an Object Compaison function

AdapdevNet

Also here is an article i wrote which has the code in C# you could convert this into VB.net quite easily

Using Reflection to test for Equality

HTH

Bones

dbones
Thanks for the tip but I completed it a while back and works like a charm.
FailBoy
+1  A: 

I have created a class to perform a deep compare of .NET Objects. See:

http://comparenetobjects.codeplex.com/

Greg Finzer