Question

I have a need to get properties and their values dynamically. My code below is failing. Can someone give me a hand? I have tried numerous examples but nothing so far.

        Dim seriesName As String = s.SeriesName
        If model.Settings.ShowNativeLanguage Then

            Dim propInfo As System.Reflection.PropertyInfo = s.GetType().GetProperty(model.Country)
            seriesName = CStr(propInfo.GetValue(s, Nothing))

        End If

This code produces the error "Object does not match target type."

Was it helpful?

Solution

The question was already answered here for C# Object does not match target type using C# Reflection

The solution is to change this line of your code:

seriesName = propInfo.GetValue(propInfo, Nothing).ToString()

to this:

seriesName = propInfo.GetValue(s, Nothing).ToString()

You need to pass the object of which you want to get the value. (More information in MSDN)

Update:

You should always check reflection results for Nothing values. So first store the output of propInfo.GetValue(s, Nothing) in a temporary variable and later on only call the ToString()-function if the object is not Nothing

OTHER TIPS

Surely that should be:

 ... propInfo.GetValue(s) ...

Normally you must pass the object representing the this instance as the first parameter. You are getting that error because it's expecting the instance s, not a PropertyInfo instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top