Overriding Members

By default, a derived class inherits all members from its base class. If you want to change the behavior of the inherited member, you need to override it. That is, you can define a new implementation of the method, property or event in the derived class.

The following modifiers are used to control how properties and methods are overridden:

C# ModifierDefinition
virtualAllows a class member to be overridden in a derived class.
overrideOverrides a virtual (overridable) member defined in the base class.
abstractRequires that a class member to be overridden in the derived class.
new ModifierHides a member inherited from a base class

In c#, Method Overriding means override a base class method in derived class by creating a method with same name and signatures to perform a different task. The Method Overriding in c# can be achieved by using override & virtual keywords along with inheritance principle.

In c#, the Method Overriding is also called as run time polymorphism or late binding.

public class Animal
{
public virtual void Greet()
{
Console.WriteLine("Hello, I'm some sort of animal!");
}
}
public class Dog : Animal
{
public override void Greet()
{
base.Greet();
Console.WriteLine("Hello, I'm a dog!");
}
}

Generally, whenever the virtual method is invoked, the run-time object will check for an overriding member in the derived class. In case, if no derived class has overridden the member, then the virtual method will be treated it as original member.

In c#, by default all the methods are non-virtual and we cannot override a non-virtual methods. In case, if you want to override a method, then you need to define it with virtual keyword.

Last modified: March 20, 2019

Author

Comments

Write a Reply or Comment