Why can't i access the age method from either class A or B? I thought because it's a protected method, derived class instances should 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 suggested by Jon Skeet--
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();
}
}
Protected means it can be used from code in the derived classes - it doesn't mean it can be used "from the outside" when working with derived classes.
The protected
modifier can be somewhat tricky, because even a derived class can only access the protected member through instances of its own class (or further derived classes).
So within the code of B, you could 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 of these is invalid because even though at execution time it's accessing the member on an instance of B
, the compiler only knows of ba
as being of type A
.
Here's the start of section 3.5.3 of the C# 5 specification, which may clarify things:
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. This restriction prevents one derived class from accessingprotected
members of other derived classes, even when the members are inherited from the same base class.
See more on this question at Stackoverflow