If we have virtual in base class and the same method is overridden in child class. By creating instance of child class and assign it to base class, then which of the method will be invoked first.
If you have a virtual method in the base class and the same method is overridden in the child class, and you create an instance of the child class and assign it to a variable of the base class type, then the overridden method in the child class will be invoked when calling the method through the base class reference. This behavior is part of polymorphism and dynamic method dispatch.
Here's an example to illustrate this concept:
using System;
class BaseClass {
public virtual void SomeMethod() {
Console.WriteLine("Base class method");
}
}
class ChildClass : BaseClass {
public override void SomeMethod() {
Console.WriteLine("Child class method");
}
}
class Program {
static void Main(string[] args) {
BaseClass instance = new ChildClass(); // Assign ChildClass instance to a BaseClass reference
instance.SomeMethod(); // Output: Child class method
// The overridden method in ChildClass will be invoked
}
}
In this example, even though the instance is of type 'BaseClass', it's actually an instance of 'ChildClass'. When you call the 'SomeMethod'method on the 'instance' using the base class reference, the overridden method in the 'ChildClass' will be invoked ('"Child class method"'), demonstrating polymorphism.
Polymorphism allows you to treat objects of derived classes as objects of their base classes, and the correct method implementation is determined based on the actual object type at runtime.