A virtual method called a derivative rather than a base

Can someone explain to me why the overridden method is called when I drop the class into the base one:

class Base { public virtual void VirtualMethod() { Console.WriteLine("Base virtual method"); } } sealed class Derived : Base { public override void VirtualMethod() { Console.WriteLine("Overriden method"); } } static void Main(String[] args) { Derived d = new Derived(); ((Base)d).VirtualMethod(); } 

I mean this code prints:

 Overriden method 

but not

 Base virtual method 

Its runtime or compilation time?

I know that I can call the base virtual method from a derivative by calling base.VirtualMethod() , but can I call it from the outside? (e.g. from Main or another class)

+4
source share
2 answers

The implementation of the method is selected based on the runtime type of the object. This is a big part of it. Anyone can use:

 public void Foo(Base b) { b.VirtualMethod(); } 

... and you don’t need to know or care about what type of execution, because polymorphism will take care of that.

I know that I can call the base virtual method from a derivative by calling base.VirtualMethod (), but can I call it from the outside?

No (at least not without some horrible hacker to call a virtual method practically not), and that is an intentional part of encapsulation. The final implementation effectively replaced the original implementation for this object.

+9
source

If you want to access the base implementation, you should not use overriding, you should use a new one. Override overrides any parent implementation, the new β€œhides” the parent implementation, so that you can access the implementation by casting as the parent object, then calling the method.

 internal class Program { private static void Main(string[] args) { Derived d = new Derived(); d.VirtualMethod(); ((Base) d).VirtualMethod(); Console.ReadLine(); } private class Base { public virtual void VirtualMethod() { Console.WriteLine("Base virtual method"); } } private sealed class Derived : Base { public new void VirtualMethod() { Console.WriteLine("Overriden method"); } } } 

This will output:

Method overcoming
Basic virtual method

+2
source

All Articles