MattCucco MattCucco - 1 year ago 52 Question

Using GetValue and System.Reflection

Using VB.Net. I'm trying to get the property values from two objects of the same class and compare them. If the values are different then i want to add them to a string showing what the values were and what they changed to. I'm having problems with the GetValue.
Here is the code for this function:

Public Function GetRowChangesList(ByVal Before As IEnumerable(Of Object), ByVal After As IEnumerable(Of Object), ByRef isNew As Boolean) As String

Dim TheseChanges As List(Of String) = Nothing

'any errors, return ""

'If Lists are both empty, return
If Before Is Nothing And After Is Nothing Then
Return ""
End If

'Figure out the object type and make sure before and after match
Dim DataTypeBefore As Type
Dim DataTypeAfter As Type

DataTypeBefore = Before.Single.GetType()
DataTypeAfter = After.Single.GetType()

'if they don't match function won't work
If DataTypeBefore IsNot DataTypeAfter Then
Return ""
End If

Dim myField As PropertyInfo() = Before.Single.GetType().GetProperties()
Dim myField2 As PropertyInfo() = After.Single.GetType().GetProperties()

'Find the changes
Dim index As Integer

For index = 0 To myField2.Length - 1
If Not myField(index).GetValue(Before) = myField2(index).GetValue(After) Then

TheseChanges(0) += ("Change happened at: " + myField(index).Name.ToString + " Values changed from: " +
myField(index).GetValue(Before).ToString + " To " + myField2(index).GetValue(After).ToString)

End If

Catch ex As Exception

'send error
SendErrorEmail(ex, "Saving changes for: '" + Before.Single.GetType().ToString)

End Try

Return TheseChanges(0)

End Function

There should only be one thing that changed if anything changes at all. That's why it just returns the first element. When I'm debugging it catches an exception every time. The errors it gives me are as follows:

If Not myField(index).GetValue(Before) = myField2(index).GetValue(After) Then error BC30199: '(' expected.
TheseChanges(0) = ("Change happened at: " + myField(index).Name.ToString + " Values changed from: " + error BC30201: Expression expected.
myField(index).GetValue(Before).ToString + " To " + myField2(index).GetValue(After).ToString) error BC37237: ')' is not a valid format specifier
End If error BC30201: Expression expected.
Next error BC30201: Expression expected.

I just tried this method and still got the same errors(Code Below). Also just tried changing '=' to isNot (didn't change anything) and I also just tried adding parens around each value and that also didn't change anything.

If myField(index).GetValue(myField(index).Name) = myField2(index).GetValue(myField(index).Name)

Answer Source


If Not myField(index).GetValue(Before) = myField2(index).GetValue(After) Then


If Not myField(index).GetValue(Before.Single) = myField2(index).GetValue(After.Single) Then


myField is created for the Type Before.Single, but you are using it with Before which is not the same type as Before.Single.