0
0
C Sharp (C#)programming~5 mins

Method overriding with virtual and override in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Method overriding lets a child class change how a method works from its parent class. This helps make programs flexible and easy to update.

When you want a child class to do something different from the parent class for the same action.
When you have a general method in a base class but need specific behavior in subclasses.
When you want to reuse code but still customize parts of it in child classes.
Syntax
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.

Examples
Base class Animal has a virtual method Speak. The Dog class changes it to say "Dog barks".
C Sharp (C#)
using System;

class Animal
{
    public virtual void Speak()
    {
        Console.WriteLine("Animal speaks");
    }
}

class Dog : Animal
{
    public override void Speak()
    {
        Console.WriteLine("Dog barks");
    }
}
The Car class overrides the Start method to show a more specific message.
C Sharp (C#)
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");
    }
}
Sample Program

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.

C Sharp (C#)
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();
    }
}
OutputSuccess
Important Notes

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.

Summary

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.