9

How to get inherited property value using reflection? I try with BindingFlags but still trigger NullReferenceException

object val = targetObject.GetType().GetProperty("position", BindingFlags.FlattenHierarchy).GetValue(targetObject, null);

position is iherited public property and has a declared value.

EDIT:

class myParent
{
    public float[] position;
    public myParent()
    {
        this.position = new float[] { 1, 2, 3 };
    }
}

class myChild : myParent
{
    public myChild() : base() { }
}

myChild obj = new myChild();
PropertyInfo p = obj.GetType().GetProperty("position", BindingFlags.Instance | BindingFlags.Public); 

I tried with several combinations with BindingFlags but p always is null :( ,

abuduba
  • 4,986
  • 7
  • 26
  • 43

2 Answers2

17

If you use the overload with BindingFlags you have to explicitly specify all the flags what you are interested.

Also note that: (from MSDN)

You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

object val = targetObject.GetType()
             .GetProperty("position", 
                          BindingFlags.FlattenHierarchy | 
                          BindingFlags.Instance | 
                          BindingFlags.Public)
             .GetValue(targetObject, null);

EDIT:

You have a position field not a property !.

(A good place to start learning the difference: Difference between Property and Field in C# 3.0+ especially this answer)

Change your position to a property:

public float[] position { get; set; }

Or you use the targetObject.GetType().GetField(... method to retrieve the field.

Community
  • 1
  • 1
nemesv
  • 138,284
  • 16
  • 416
  • 359
3
BindingFlags.FlattenHierarchy

works only for static members. Be sure to specify

BindingFlags.Instance | BindingFlags.Public

and you should get inherited properties.

armen.shimoon
  • 6,303
  • 24
  • 32