how can I acsess a private member of base class in derived class? give me an example .
Thank you
yours
chaithu
how can I acsess a private member of base class in derived class? give me an example .
Thank you
yours
chaithu
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AlanPosted Jul 31, 2008, 5:09 AM
Here's a quick example of obtaining the value of a private field in the base class using reflection:
using System;
using System.Reflection;
class Program
{
static void Main()
{
Derived d = new Derived();
Console.WriteLine("The value of parentInt is {0}",d.DerivedMethod());
Console.ReadLine();
}
}
class Parent
{
private int parentInt = 3;
}
class Derived : Parent
{
public int DerivedMethod()
{
Type t = this.GetType().BaseType;
BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic;
FieldInfo fi = t.GetField("parentInt", bf);
return (int)fi.GetValue(this);
}
}
Notice that you can apply the FieldInfo.GetValue() method to the current Derived instance rather than creating a separate Parent instance. This is because the private field is still inherited by Derived even though it's not directly accessible by code within it.
AlanPosted Jul 31, 2008, 4:26 AM
You can't except by using reflection.
I can give you an example of that if you can let me know what type of private member you want to access.