Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change reference of Base object to Derived which was instatiated as Derived type

Tags:

c#

inheritance

Why am i not able to access M3 method from Derived ? Intellisense shows only M1 and M2 from Base class. How can i change the reference of bc from Base type to Refernce Type, so that i can access M3 method.

class Program
{
    static void Main(string[] args)
    {
        Base bc = new Derived();
        bc.M3():// error
    }
}

class Base
{
    public void M1()
    {
        Console.WriteLine("M1 from BASE.");
    }
    public void M2()
    {
        Console.WriteLine("M2 from BASE.");
    }
}

class Derived : Base
{
    public void M3()
    {
        Console.WriteLine("M3 from DERIVED.");
    }
}
like image 221
Alex David Avatar asked Dec 25 '22 13:12

Alex David


2 Answers

The compiler must resolve the name M3 at compile time. This is being invoked on a reference of type Base and Base has no member of that name. The fact that it happens to point to an instance of Derived at runtime has no bearing here because the compiler is looking at the information available at compile time.

Yes in this specific case the compiler could see that bc is always initialized to a Derived value hence it should look there. However this is just not how the c# compiler works. It looks only at the compile time type of the reference involved

like image 84
JaredPar Avatar answered Dec 28 '22 06:12

JaredPar


Because you upper cast your type to a base class, so the set of all available members is reduces to those ones available in Base.

Derived bc = new Derived();
bc.M3():// CORRECT

or simply

var bc = new Derived();
bc.M3():// CORRECT

If you need to work with Base class for polymorphism in your app and need to use M3() consider moving it in Base class

like image 42
Tigran Avatar answered Dec 28 '22 05:12

Tigran