views:

278

answers:

2

I have an object which has a huge number of properties. I'd like to get the value of each of those properties by simply looping through the properties collection of the object.

I've looked into the PropertyInfo.GetValue() method however it's not making much sense in the context I have.

Here's an example of what i'm trying to do (this code doesn't work btw):

foreach(var item in dataObjects)
  {
    foreach(PropertyInfo prop in item.GetType().GetProperties())
    {
      String value = prop.GetValue().ToString()
    }
  }

I realise now that getting the value of a property isn't this easy. What am I missing? I don't really understand what I need to pass to the GetValue() method because I simply want the value of the property I'm calling that method on.

Thanks for any help clarifying this for me. I've spent a couple of hours here just banging my head against the desk.

+3  A: 

You need to provide the specific object on which you want to call the property in question:

prop.GetValue(item, null);

The PropertyInfo is just metatdata about the property on the type, not on the specific object instance. The PropertyInfo doesn't know which instance it came from (if any) - just the type/class it came from.

You can almost think of the PropertyInfo as just the name of the property. That's not enough information to do anything with it alone - we then have to say "get the value of the property with this name on... what?" On the object we provide.

Rex M
+1  A: 

PropertyInfo represents the property machinery itself (type, get method, set method, et cetera), not a property bound to a specific instance. If the property is nonstatic, you must provide an instance to read that property from -- that's the first parameter to GetValue. In other words, if pi is a PropertyInfo representing the Test property on some class and someObject is an instance of that class:

object a = someObject.Test;
object b = pi.GetValue(someObject, null);

both lines there get the value of the same property on the same object. If the property is static, you don't need to pass the instance, obviously (pass null instead). The second parameter is the index for indexed properties -- C# does not support indexed properties (it supports indexers, which are not exactly the same), so you will likely never need to pass anything but null for that second parameter unless you're working with some type from an assembly written in a language that does support indexed properties (like VB, I believe).

Josh Petrie