Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 721
Petr Avatar asked Jun 01 '10 14:06

Petr


2 Answers

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.

like image 93
Martin Eve Avatar answered Sep 23 '22 11:09

Martin Eve


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.

like image 25
this. __curious_geek Avatar answered Sep 22 '22 11:09

this. __curious_geek