Are private members inherited in C#?
Just seen one tutorial saying that:
Class Dog
{
private string Name;
}
Class SuperDog:Dog
{
private string Mood;
}
Then there was an UML displaying that SuperDog will inherit Name as well. I have tried but to me it seems that only public members are inherited. At least I could not access Name unless it was declared as public.
Solution 1:
A derived class has access to the public, protected, internal, and protected internal members of a base class. Even though a derived class inherits the private members of a base class, it cannot access those members. However, all those private members are still present in the derived class and can do the same work they would do in the base class itself. For example, suppose that a protected base class method accesses a private field. That field has to be present in the derived class in order for the inherited base class method to work properly.
From: http://msdn.microsoft.com/en-us/library/ms173149.aspx
So, technically, yes, but practically, no.
Solution 2:
Everything from the base class is inherited to derived class. members marked private are not accessible to derived classes for integrity purpose, should you need to make them accessible in derived class, mark the members as protected.
There are various levels of members' accessibility in context of inheritance.
public
: all public members of the base-class are accessible within the derived-class and to the instances of derived-class.
protected
: all protected members of the base-class are accessible within the derived-class and not to the instances of derived-class.
protected internal
: all protected internal members of the base-class are accessible within the derived-class and to the instances of derived-class created within the same assembly.
internal
: all internal members of the base-class are accessible within the derived-class and to the instances of derived-class within the same assembly.
private
: no private members of the base-class are accessible within the derived-class and to the instances of derived-class.
private protected
: The type or member can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class.
Solution 3:
SuperDog will inherit the Name field, yes.
SuperDog will NOT have access to the field though, so there is no practical use (as far as SuperDog is concerned).