Method overriding lets a child class change how a method works from its parent class. This helps make programs flexible and easy to update.
Method overriding with virtual and override in C Sharp (C#)
class BaseClass { public virtual void MethodName() { // base method code } } class ChildClass : BaseClass { public override void MethodName() { // new method code } }
virtual keyword marks a method in the base class that can be changed in child classes.
override keyword tells the compiler that the child class is changing the base class method.
Animal has a virtual method Speak. The Dog class changes it to say "Dog barks".using System; class Animal { public virtual void Speak() { Console.WriteLine("Animal speaks"); } } class Dog : Animal { public override void Speak() { Console.WriteLine("Dog barks"); } }
Car class overrides the Start method to show a more specific message.using System; class Vehicle { public virtual void Start() { Console.WriteLine("Vehicle starting"); } } class Car : Vehicle { public override void Start() { Console.WriteLine("Car starting with key"); } }
This program shows how the Student class changes the Greet method from Person. Even when a Student is used as a Person type, the overridden method runs.
using System; class Person { public virtual void Greet() { Console.WriteLine("Hello from Person"); } } class Student : Person { public override void Greet() { Console.WriteLine("Hello from Student"); } } class Program { static void Main() { Person p = new Person(); p.Greet(); Student s = new Student(); s.Greet(); Person ps = new Student(); ps.Greet(); } }
If you forget virtual in the base class, you cannot override the method in child classes.
Use override to make sure you are actually changing a method from the base class.
Calling the method on a base class reference that points to a child object runs the child's version if overridden.
Use virtual in the base class to allow method changes.
Use override in the child class to change the method.
This helps customize behavior while keeping a shared structure.