Reputation: 35194
I'm trying to get the value from a PropertyInfo[]
, but I can't get it to work:
foreach (var propertyInfo in foo.GetType().GetProperties())
{
var value = propertyInfo.GetValue(this, null);
}
Exception:
Object does not match target type.
Isn't this how it's supposed to be done?
Upvotes: 18
Views: 23979
Reputation: 27962
You are processing properties declared in foo
's type, but try to read their values from this
, which apparently isn't of the same type.
Upvotes: 4
Reputation: 245399
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);
Upvotes: 7
Reputation: 1500065
You're trying to get properties from this
when you originally fetched the PropertyInfo
s 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.
Upvotes: 32