Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection: different ways to retrieve property value

I'm retrieving an IEnumerable list of properties via following code:

BindingFlags bindingFlag = BindingFlags.Instance | BindingFlags.Public;  
var dataProperties = typeof(myParentObject).GetProperties(bindingFlag);

Then I'm iterating through the list and retrieving the value for each property.

I've come across two different approaches to doing this, and just wondered what the difference is between them:

1)

object propertyValue = property.GetGetMethod().Invoke(myObject, null);

2)

object propertValue = property.GetValue(myObject, null)
like image 255
jules Avatar asked Mar 03 '10 11:03

jules


1 Answers

In fact, there is no difference. You can see the implementation of GetValue using Reflector:

public override object GetValue(object obj, BindingFlags invokeAttr,
                                Binder binder, object[] index,
                                CultureInfo culture)
{
    MethodInfo getMethod = this.GetGetMethod(true);
    if (getMethod == null)
    {
        throw new ArgumentException(
                             Environment.GetResourceString("Arg_GetMethNotFnd"));
    }
    return getMethod.Invoke(obj, invokeAttr, binder, index, null);
}

The actual type here is RuntimePropertyInfo (PropertyInfo is an abstract class that does not provide implementation for GetValue).

like image 125
Elisha Avatar answered Nov 08 '22 19:11

Elisha