Virtual vs Override
Virtual means making another version of same method in a child class, simply check for newer implementations before calling but abstract method is guaranteed to be overridden in all derived classes. In programming terminology it means that it can modify a method, property, indexer or event declaration and allow it to be overridden. A method cannot be overridden in a derived class unless it is declared as virtual or abstract. For abstract class no implementation is required in the base class because it will be redefined in the derived class.
When a virtual method is called on a reference, the actual type of the object that the reference refers to is used to decide which method implementation to use. When a method of a base class is overridden in a derived class, the version in the derived class is used.
Example: Using override
using System;
namespace HelloWorld
{
class Hello
{
static void Main()
{
Base b = new Derived();
b.SomeMethod();
Derived d = new Derived();
d.SomeMethod();
}
}
public class Base {
public virtual void SomeMethod()
{
Console.WriteLine("From base class");
}
}
public class Derived: Base {
public override void SomeMethod()
{
Console.WriteLine("From derived class");
}
}
}
Output:
From derived class
From derived class
Example: Using New
using System;
namespace HelloWorld
{
class Hello
{
static void Main()
{
Base b = new Derived();
b.SomeMethod();
Derived d = new Derived();
d.SomeMethod();
}
}
public class Base {
public virtual void SomeMethod()
{
Console.WriteLine("From base class");
}
}
public class Derived: Base {
public new void SomeMethod()
{
Console.WriteLine("From derived class");
}
}
}
Output:
From base class
From derived class
Using the new keyword instead of override, the method in the derived class doesn’t override the method in the base class.
If you don’t specify new or override, the compiler will give a warning but the result output will be same as new.
Base b = new Derived();
Here I am creating the instance of Derived class but stored the reference in base. This is valid because Derived class is inherited from base. Derived class can perform all the operations that a base class can do but Base class will not be able to perform the operations of Derived class. Therefore you cannot reverse the declaration like Derived d = new Base().
When non-virtual method is called, the compiler already knows the actual method but for virtual methods the compiler has to lookup from down to up the hierarchy.
An overriding property declaration may include the sealed modifier. The use of this modifier prevents a derived class from further overriding the property. The accessors of a sealed property are also sealed.
Hello,
It shouldn’t be like this in the Hello class?
Base b = new Base();