If we inherit a class, do the private variables of base class also get inherited?
No, private variables in a base class are not directly accessible or inherited by the derived class in C#. Private variables are part of the implementation details of the base class, and they are not accessible to the derived class. Inheritance in C# doesn't include private members.
Private members, including private fields, private methods, and private nested classes, are only accessible within the class where they are defined. They are not accessible from any derived classes, even if you inherit from the base class.
Here's an example to illustrate this concept:
public class BaseClass
{
private int privateVariable = 10;
public void BaseMethod()
{
Console.WriteLine("Base method");
Console.WriteLine("Private variable value: " + privateVariable); // Accessible within the base class
}
}
public class DerivedClass : BaseClass
{
public void DerivedMethod()
{
Console.WriteLine("Derived method");
// Cannot access privateVariable here (it is not inherited)
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass derivedObj = new DerivedClass();
derivedObj.BaseMethod(); // Output: Base method
derivedObj.DerivedMethod(); // Output: Derived method
}
}
In this example, the 'BaseClass' has a private variable 'privateVariable'. It is only accessible within the 'BaseClass' itself. The 'DerivedClass' inherits the 'BaseMethod()' from the 'BaseClass', and it can call this method, but it cannot access or modify the private variable directly.
Private members are encapsulated within the class that declares them, and they are not visible or accessible outside of that class, including derived classes. Only 'public' and 'protected' members are inherited by derived classes and can be accessed from the derived class or its instances.
If you want to provide access to the private variables in the base class to the derived class, you can do so by using properties or protected members, which allow controlled access to the underlying private variables.