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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
AlanRank #669 · 3.6K reputationPosted Jul 31, 2008, 12:26 AM EDT
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.
AlanRank #669 · 3.6K reputationPosted Jul 31, 2008, 1:09 AM EDT
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.