Get private property of a private property using reflection

31.6k Views Asked by At
public class Foo
{
    private Bar FooBar {get;set;}

    private class Bar
    {
        private string Str {get;set;}
        public Bar() {Str = "some value";}
    }
 }

If I've got something like the above and I have a reference to Foo, how can I use reflection to get the value Str out Foo's FooBar? I know there's no actual reason to ever do something like this (or very very few ways), but I figure there has to be a way to do it and I can't figure out how to accomplish it.

edited because I asked the wrong question in the body that differs from the correct question in the title

2

There are 2 best solutions below

3
On BEST ANSWER

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);
0
On

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).