Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Accessing Base Private Members from Child

0.00/5 (No votes)
20 Oct 2011LGPL32 min read 13.2K  
Accessing base private members from child

I have been thinking about how to prove to myself that base class members do get inherited to their child classes (sub classes) but still they remain private. Actually, I had read these lines in many places in my earlier days. But I 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, it's a known fact you might think.

Just to let you know this idea popped up in my mind when I started my real programming career. So it's a 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 it, 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:

C#
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);

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 something like generics wherein 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., without using BaseType property. If you know, kindly comment.

Thanks for reading!

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)