Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get protected property value of base class using reflection

Tags:

c#

dictionary

I would like to know if it is possible to access the value of the ConfigurationId property which is located in the base class of the object and it's private. I have tried to do it with reflection with no luck. enter image description here

like image 782
Michal Olechowski Avatar asked Aug 24 '15 14:08

Michal Olechowski


2 Answers

To access ConfigurationId property i have used following code:

SubsetController controller = new SubsetController(new CConfigRepository(new FakeDataContextRepository()));

var myBaseClassProtectedProperty=
            controller.GetType().BaseType
                .GetProperty("CCITenderInfo", BindingFlags.NonPublic | BindingFlags.Instance)
                .GetValue(controller);

var myProtectedProperty =
            CCITenderInfo.GetType()
                .GetProperty("ConfigurationId", BindingFlags.Public |     BindingFlags.Instance)
                .GetValue(myBaseClassProtectedProperty);
like image 163
Michal Olechowski Avatar answered Oct 10 '22 21:10

Michal Olechowski


Assuming the following parent and child class:

class BaseClass
{
    private string privateField = "I'm Private";
}

class ChildClass : BaseClass
{

}

You can read privateField's value from a ChildClass instance using reflection like this:

ChildClass childInstance = new ChildClass();
object privateFieldValue = childInstance.GetType().BaseType
    .GetField("privateField", BindingFlags.NonPublic | BindingFlags.Instance)
    .GetValue(childInstance);
Console.WriteLine(privateFieldValue); // I'm Private
like image 44
Saeb Amini Avatar answered Oct 10 '22 22:10

Saeb Amini