Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Derived Class using Parent Method

Tags:

c#

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();
    }
}
like image 263
Baahubali Avatar asked Oct 21 '25 11:10

Baahubali


1 Answers

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 a protected 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 accessing protected members of other derived classes, even when the members are inherited from the same base class.

like image 164
Jon Skeet Avatar answered Oct 23 '25 00:10

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!