PropertyInfo.GetValue() "Object does not match target type."

StevenMcD picture StevenMcD · Nov 22, 2008 · Viewed 23k times · Source

I'm digging into Reflection for the first time and I'm truely stuck. I've googled everything I can think of. I'm 90% where I wanna be now.

I'm trying to return the value of a Property in a custom class through Reflection.

Here's my class declaration:

Public Class Class2
    Private newPropertyValue2 As String

    Public Property NewProperty2() As String
        Get
            Return newPropertyValue2
        End Get
        Set(ByVal value As String)
            newPropertyValue2 = value
        End Set
    End Property   
End Class

The class I've written to look at the class through reflection looks like this:

Public Class ObjectCompare
    Private _OriginalObject As PropertyInfo()

    Public Property OriginalObject() As PropertyInfo()
        Get
            Return _OriginalObject
        End Get
        Set(ByVal value As PropertyInfo())
            _OriginalObject = value
        End Set
    End Property

    Public Sub CompareObjects()
        Dim property_value As Object

        For i As Integer = 0 To OriginalObject.Length - 1
            If OriginalObject(i).GetIndexParameters().Length = 0 Then
                Dim propInfo As PropertyInfo = OriginalObject(i)

                Try
                    property_value = propInfo.GetValue(Me, Nothing)
                Catch ex As TargetException
                End Try   
            End If
        Next
    End Sub
End Class

I put a breakpoint on the property_value = propInfo.GetValue(Me, Nothing) line to see what the result is.

Here's how I call my code:

Dim test As New Class2
test.NewProperty2 = "2"

Dim go As New ObjectCompare
Dim propInf As PropertyInfo()
propInf = test.GetType.GetProperties()

go.OriginalObject = propInf

go.CompareObjects()

Through reflection I can see the PropertyName and Type, all I need is the value of the Property! Now when I get to the breakpoint, I get a TargetException and the error message says "Object does not match target type." Its now 1AM in the morning and I'm wrecked, any help right now would be appreciated. I've searched MSDN and Google to death and then on last time for fun ;)

Answer

tvanfosson picture tvanfosson · Nov 22, 2008

Me refers to the ObjectCompare object, which is different than the class from which the PropertyInfo objects were derived (Class2). You need to also pass in an object of the type from which you retrieved the PropertyInfo objects.

Public Sub CompareObjects(ByVal It as Object)
    Dim property_value As Object

    For i As Integer = 0 To OriginalObject.Length - 1
        If OriginalObject(i).GetIndexParameters().Length = 0 Then
            Dim propInfo As PropertyInfo = OriginalObject(i)

            Try
                property_value = propInfo.GetValue(It, Nothing)
            Catch ex As TargetException
            End Try   
        End If
    Next
End Sub

go.CompareObjects(test)