Reputation: 157
How Can BaseClass Private function be Accessible into DerivedClass in C#?
Upvotes: 4
Views: 4023
Reputation: 6029
With reflection:
FieldInfo f = typeof(Foo).GetField("someField", BindingFlags.Instance | BindingFlags.NonPublic);
fd.SetValue(obj, "New value");
Upvotes: 3
Reputation: 1503469
This answer is for completeness only. In almost all cases, use the suggestions in the other answers.
The other answers are all correct, except there's one situation in which a derived class can access a private member in the base class: when the derived class is a nested type of the base class. This can actually be a useful feature for mimicking Java enums in C#. Sample code (not of Java enums, just the "accessing a private member" bit.)
public class Parent
{
private void PrivateMethod()
{
}
class Child : Parent
{
public void Foo()
{
PrivateMethod();
}
}
}
Upvotes: 4
Reputation: 15984
It can't. If you want the method to be accessible to derived classes then you need to make it protected
instead.
Upvotes: 2
Reputation: 391664
Either:
private
to protected
Of the 4, I would chose 1 if it's a private property or method, and 2 if it's a private field. I would add a protected property around the field.
Upvotes: 11
Reputation: 1039438
It can't. That's the whole purpose of the private access modifier:
The type or member can be accessed only by code in the same class or struct.
Of course you could always use reflection.
Upvotes: 5