How Can BaseClass Private function be Accessible into DerivedClass in C#?
5 Answers
Either:
- Elevate its access from
privatetoprotected - or, add another protected member that accesses it, and use this instead from the derived class
- or, use reflection
- or, change the code so you don't need to access it
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.
Comments
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.
1 Comment
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();
}
}
}