Get private property of a private property using reflection
You can use the GetProperty
method along with the NonPublic
and Instance
binding flags.
Assuming you have an instance of Foo
, f
:
PropertyInfo prop =
typeof(Foo).GetProperty("FooBar", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo getter = prop.GetGetMethod(nonPublic: true);
object bar = getter.Invoke(f, null);
Update:
If you want to access the Str
property, just do the same thing on the bar
object that's retrieved:
PropertyInfo strProperty =
bar.GetType().GetProperty("Str", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo strGetter = strProperty.GetGetMethod(nonPublic: true);
string val = (string)strGetter.Invoke(bar, null);
There is a way to slightly simplify Andrew's answer.
Replace the calls to GetGetMethod()
+ Invoke()
with a single call to GetValue()
:
PropertyInfo barGetter =
typeof(Foo).GetProperty("FooBar", BindingFlags.NonPublic | BindingFlags.Instance);
object bar = barGetter.GetValue(f);
PropertyInfo strGetter =
bar.GetType().GetProperty("Str", BindingFlags.NonPublic | BindingFlags.Instance);
string val = (string)strGetter.GetValue(bar);
I did some testing, and I didn't find a difference, then I found this answer, which says that GetValue()
calls GetGetMethod()
with error checking, so there is no practical difference (unless you worry about performance, but when using Reflection I guess that you won't).