I am making a simple C# console application to test inheritance but when I add 2 new classes and inherit one with another ( Mammal:Animal ) and make an object of mammal in the Program.cs class i-e
Program.cs
Mammal mam = new Mammal();
mam.see(only public function are showing of animal not the protected member of function)
Animal.cs
class Animal
{
protected void check()
{}
public void see()
{}
}
Mammal.cs
class Mammal:Animal
{
public void hair()
{}
}
Can't figure out why it is not allowing, as protected allows to inherit if they are in its hierarchy.
The code within Mammals
has access to protected members of Animals
, but only via an expression of type Mammals
or a subtype.
From outside the class - which I assume this is - there's no access to protected members.
From section 3.5.3 of the C# 5 specification (emphasis mine):
When a
protected
instance member is accessed outside the program text of the class in which it is declared, and when aprotected internal
instance member is accessed outside the program text of the program in which it is declared, the access must take place within a class declaration that derives from the class in which it is declared. Furthermore, the access is required to take place through an instance of that derived class type or a class type constructed from it.
(As noted by Jonathan Reinhart, you almost certainly want these types to be called Mammal
and Animal
, by the way.)
See more on this question at Stackoverflow