Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get PropertyInfo value

Tags:

c#

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?

like image 352
Johan Avatar asked Jan 31 '12 14:01

Johan


People also ask

What does GetValue return c#?

GetValue(Object) Returns the property value of a specified object.

What is PropertyInfo?

< Previous Next > The PropertyInfo class discovers the attributes of a property and provides access to property metadata. The PropertyInfo class is very similar to the FieldInfo class and also contains the ability to set the value of the property on an instance.

How do you set property value?

To set the value of an indexed property, call the SetValue(Object, Object, Object[]) overload. If the property type of this PropertyInfo object is a value type and value is null , the property will be set to the default value for that type.


2 Answers

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.

like image 191
Jon Skeet Avatar answered Sep 23 '22 02:09

Jon Skeet


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);
like image 42
Justin Niessner Avatar answered Sep 23 '22 02:09

Justin Niessner