Derived class using parent method
Why can't I access the age method from grades A or B? I thought because it is a protected method, should derived class instances be able to use it?
class Program
{
public static void Main(string[] args)
{
}
public static void Test(A test)
{
A a = new A();
B b = new B();
Console.WriteLine(a.Age());
Console.WriteLine(b.Age());
}
}
public class A
{
public virtual string Name { get { return "TestA"; } }
protected string Age() { return "25";}
}
public class B : A
{
public override string Name { get { return "TestB"; } }
public string Address { get; set; }
}
--- As Jon Skeet suggested -
public class B : A
{
public override string Name { get { return "TestB"; } }
public string Address { get; set; }
public void Testing()
{
B a = new B();
a.Age();
}
}
source to share
Protected means that it can be used from code in derived classes - it does not mean that it can be used "outside" when working with derived classes.
The modifier protected
can be somewhat tricky because even a derived class can only access the protected member through instances of its own class (or additional derived classes).
So, in code B, you can write:
A a = new A();
Console.WriteLine(a.Age()); // Invalid - not an instance of B
B b = new B();
Console.WriteLine(b.Age()); // Valid - an instance of B
A ba = b;
Console.WriteLine(ba.Age()); // Invalid
The last one is invalid because although it accesses a member in an instance at runtime B
, the compiler only knows about ba
as a type A
.
This is where section 3.5.3 of the C # 5 spec starts, which might clarify things:
When an instance member
protected
is accessed outside of the program text of the class in which it is declared, and when the instance memberprotected internal
is accessible outside of the program code in which it is declared, the access must occur in the class declaration that derives from the class in which it is declared. In addition, access must be through an instance of that derived class type or the type of a class built from it. This limitation prevents one derived class from accessingprotected
members of other derived classes, even if the members inherit from the same base class.
source to share