Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get private property of a private property using reflection

Tags:

c#

reflection

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

like image 936
claudekennilol Avatar asked Jun 10 '15 17:06

claudekennilol


People also ask

How to set private property using reflection c#?

This is how you can write to the private property by using Reflection: //Example class public class Person { public string Name { get; private set; } } var person = new Person(); //Cannot do this due to the private set:er: //person.Name = "Foo"; //Set value by using Reflection: person. GetType(). GetProperty("Name").

Can reflection access private members c#?

Occasionally, when writing C# unit tests, you will come across classes with private members that need to be accessed or modified to properly test the system. In these cases, reflection can be used to gain access to private members of a class.

Can properties be private?

Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property.

What are reflections in C#?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.


1 Answers

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);
like image 160
Andrew Whitaker Avatar answered Oct 13 '22 01:10

Andrew Whitaker