Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get property value dynamically

Tags:

People also ask

How do you access object properties dynamically?

To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .

What is ExpandoObject in C#?

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.


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.