C# · CodeProject · Dotnet

Accessing Base private members from Child TIP

Dear Reader,

I had been thinking about how to prove myself that base class members do get inherited to their child classes (sub classes) but still they remain private. Actually this lines i had read in many places in my earlier days. But always wanted to validate it.

So i set to write code for that and hence i started using Reflection. It’s the only way one can open the package (object) and see inside it at run time, because i knew this inheritance really come alive at run time. Of course its known fact you might think.

Just to let you know this idea popped up in my mind when i started my real programming career after fresher stage. So its shame that i am writing about it now.

To access members, i am using Type.BaseType.GetMethods() API and for fields i am using Type.BaseType.GetFields() API.

This is how i did, although i must honestly admit that the entire idea i could not conceive by myself on how to implement so i had to take a look at Stackoverflow threads on the same.

So below is the code:

public class Base
{
int basePrivateVariable;

void Hello() { }
}

public class Child : Base
{
}

BindingFlags flag = BindingFlags.NonPublic | BindingFlags.Instance;
var privateMethods = typeof(Child).BaseType.GetMethods(flag);
var privateFields = typeof(Child).BaseType.GetFields(flag);

Although i am still looking (curious or craziness of mine you can say) to achieve the same without using BaseType property on a Type.Β  No this is not solving any real world problem for me, but i am just curious because using BaseType property of Type class i am convinced that while writing it in my code editor (visual studio) i know for sure that i am accessing base class members because i am using BaseType property. So i want some thing like generics where in at compile time you’re not convinced/know what type you will be accessing or what type your block code gets. The same i want to access base class members by using only Child object and its level reflection API i.e with out using BaseType property. If you know, kindly comment.

Thanks πŸ™‚

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s