Monday, March 19, 2007

How to Use Reflection to Compare Two Objects

The Code


Private Function IsEqualTo(ByVal objA As Object, ByVal objB As Object) As Boolean

Dim different As Boolean = False
Dim type1 As Type = objA.GetType
Dim props() As PropertyInfo = type1.GetProperties

For Each p As PropertyInfo In props
Dim pValue As Object = p.GetValue(objA, Nothing)
Dim pValue2 As Object = p.GetValue(objB, Nothing)

If pValue <> pValue2 Then
different = True
Exit For
End If
Next

Return Not different

End Function


This code snippet is pretty simple. It uses reflection to iterate over the properties of one Object (objA) and compares each property to the other object (objB) of the same type.

How would you use it?



This example will return "equal"


Dim objA as New Person
Dim objB as New Person

objA.FirstName = 'John'
objA.LastName = 'Smith'
objA.Phone = '555-1234'

objB.FirstName = 'John'
objB.LastName = 'Smith'
objB.Phone = '555-1234'

If IsEqualTo(objA,objB) Then
MsgBox("equal")
Else
MsgBox("not equal")
End If




This example will return "not equal"



Dim objA as New Person
Dim objB as New Person

objA.FirstName = 'John'
objA.LastName = 'Smith'
objA.Phone = '555-1234'

objB.FirstName = 'John'
objB.LastName = 'Smith'
objB.Phone = '555-1235'

If IsEqualTo(objA,objB) Then
MsgBox("equal")
Else
MsgBox("not equal")
End If


1 comment:

Prema Tiwari said...
This comment has been removed by the author.