Gottfried Lesigang
Gottfried Lesigang

Reputation: 67311

Get value via Reflection from double nested class

currently I'm trying to get the value of a property from a nested class. Unfortunately I'm getting a parameter as object. I know the interal structure, but I couldn't puzzle out, how to reach through to the property.

For easy testing I prepared some lines of code:

namespace ns{
    public class OuterClass{
        public InnerClass ic = new InnerClass();
    }
    public class InnerClass {
        private string test="hello";
        public string Test { get { return test; } }
    }
}

Calling this directly is easy:

var oc = new ns.OuterClass();
string test = oc.ic.Test;

But when I try to get the value via reflection, I run into System.Reflection.TargetException:

object o = new ns.OuterClass();
var ic_field=o.GetType().GetField("ic");
var test_prop = ic_field.FieldType.GetProperty("Test");
string test2 = test_prop.GetValue(???).ToString();

What do I have to use as the object within GetValue()?

Upvotes: 2

Views: 1094

Answers (1)

Kirk Woll
Kirk Woll

Reputation: 77546

You need to get the value of ic from the FieldInfo:

object ic = ic_field.GetValue(o);

Then you pass that to test_prop.GetValue:

string test2 = (string)test_prop.GetValue(ic, null);

Upvotes: 3

Related Questions