Get PropertyInfo value

You're getting that exception because this isn't the same type as foo.

You should make sure you're getting the properties for the same object that you're going to try to get the value from. I'm guessing from your code that you're expecting this to be foo inside the scope of the loop (which isn't the case at all), so you need to change the offending line to:

var value = propertyInfo.GetValue(foo, null);

You're trying to get properties from this when you originally fetched the PropertyInfos from foo.GetType(). So this would be more appropriate:

var value = propertyInfo.GetValue(foo, null);

That's assuming you want to effectively get foo.SomeProperty etc.

Tags:

C#