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.");
}
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With