If derived class does not override the method,which version should be called?

c#, overriding, polymorphism

Solution

In your source code, you are always doing simple inheritance without any polymorphic behavior. You are always created instance of derived class and assigning it to derived class instance variable.

DerivedClass d = new DerivedClass(); // here no polymorphism, and only inheritance is there

So When you will call method using class variable, it will always call DerivedClass method, no matter if the method is virtual or not in parent class.

In Polymorphism, your programs do not know the exact type of class on which you are calling the method (this concept is called late-binding). As in example below:

BaseClass b = new DerivedClass(); // here b is a base class instance but initiated using derived class

After calling b.method() it will do late binding and will show polymorphic behavior (only if the method has been set virtual in the base class)

NOTE: The virtual keyword delays binding to correct version of method to runtime and is core keywork to implement polyphorphism. So for exact polymorphic behavior, declare methods as virtual in parent class, and then in child class, ovverride that method.

Problem

I am trying understand the need of override and virtual in C#,so I wrote the following code: ``` using System; namespace Override { class Base { public virtual void method() { Console.WriteLine("Base method"); } } class Derived : Base { public override void method() { Console.WriteLine("Derived method"); } } class Program { static void Main(string[] args) { Derived d = new Derived(); d.method(); } } } ``` And I was expecting "Derived method" to be called and printed.Then I wrote the following code without using virtual/override combination. ``` using System; namespace Override { class Base { public void method() { Console.WriteLine("Base method"); } } class Derived : Base { public void method() { Console.WriteLine("Derived method"); } } class Program { static void Main(string[] args) { Derived d = new Derived(); d.method(); } } } ``` And I got the same result i.e. "Derived method" called and printed.My question is if the code worked without virtual/override as I expected,what is the need of them? or am I missing something here?

Original source