Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property reflection - How to get value?

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."

like image 938
prison-mike Avatar asked Nov 05 '25 18:11

prison-mike


1 Answers

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

like image 111
peter Avatar answered Nov 09 '25 10:11

peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!