C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# virtual Keyword

In C#, the virtual keyword is used to indicate that a method, property, indexer, or event can be overridden in a derived class. This allows you to provide a base implementation in a base class while allowing derived classes to extend or modify the implementation as needed. In this tutorial, we'll cover the basics of using the virtual keyword in C#.

  • Declare a virtual method in a base class

To declare a virtual method in a base class, use the virtual keyword followed by the method signature.

public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("The animal makes a sound");
    }
}
  • Override a virtual method in a derived class

To override a virtual method in a derived class, use the override keyword followed by the method signature.

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("The dog barks");
    }
}
  • Call a virtual method

When you call a virtual method, the runtime determines the appropriate implementation to call based on the actual type of the object, not the declared type of the variable.

Animal myAnimal = new Animal();
myAnimal.MakeSound(); // Output: "The animal makes a sound"

Animal myDog = new Dog();
myDog.MakeSound(); // Output: "The dog barks"
  • Virtual properties and indexers

In addition to methods, you can also declare virtual properties and indexers in a base class.

public class Person
{
    public virtual string Name { get; set; }
}

public class Employee : Person
{
    private string _name;

    public override string Name
    {
        get { return _name; }
        set { _name = value.ToUpper(); }
    }
}
  • Virtual events

You can declare virtual events in a base class and allow derived classes to override the add and remove accessors.

public class BaseClass
{
    public virtual event EventHandler MyEvent;

    protected virtual void OnMyEvent(EventArgs e)
    {
        MyEvent?.Invoke(this, e);
    }
}

public class DerivedClass : BaseClass
{
    private event EventHandler _myEvent;

    public override event EventHandler MyEvent
    {
        add { _myEvent += value; }
        remove { _myEvent -= value; }
    }

    protected override void OnMyEvent(EventArgs e)
    {
        _myEvent?.Invoke(this, e);
    }
}

In this tutorial, we covered the basics of using the virtual keyword in C#. The virtual keyword allows you to declare methods, properties, indexers, or events that can be overridden in a derived class. This enables derived classes to extend or modify the base implementation as needed, and the runtime determines the appropriate implementation to call based on the actual type of the object.

  1. C# virtual keyword explanation

    The virtual keyword in C# is used to define a method, property, or indexer in a base class that can be overridden in derived classes. It allows for runtime polymorphism and dynamic dispatch.

    public class BaseClass
    {
        public virtual void MyMethod()
        {
            Console.WriteLine("BaseClass MyMethod");
        }
    }
    
  2. Using virtual keyword in C#

    To use the virtual keyword, declare a method, property, or indexer in the base class with the virtual modifier.

    public class BaseClass
    {
        public virtual void MyMethod()
        {
            Console.WriteLine("BaseClass MyMethod");
        }
    }
    
    public class DerivedClass : BaseClass
    {
        public override void MyMethod()
        {
            Console.WriteLine("DerivedClass MyMethod");
        }
    }
    
  3. C# virtual vs. override

    The virtual keyword is used to declare a method that can be overridden in derived classes, while the override keyword is used in the derived class to provide a specific implementation for the virtual method.

    public class BaseClass
    {
        public virtual void MyMethod()
        {
            Console.WriteLine("BaseClass MyMethod");
        }
    }
    
    public class DerivedClass : BaseClass
    {
        public override void MyMethod()
        {
            Console.WriteLine("DerivedClass MyMethod");
        }
    }
    
  4. Polymorphism with virtual methods in C#

    Virtual methods enable polymorphism, allowing different derived classes to provide their own implementation while being accessed through a common interface.

    BaseClass obj = new DerivedClass();
    obj.MyMethod(); // Calls the overridden method in DerivedClass
    
  5. Abstract classes and virtual methods in C#

    Abstract classes can also have virtual methods, and these methods must be implemented by derived classes. Abstract methods are implicitly virtual.

    public abstract class MyBaseClass
    {
        public abstract void MyAbstractMethod();
    }
    
    public class DerivedClass : MyBaseClass
    {
        public override void MyAbstractMethod()
        {
            Console.WriteLine("DerivedClass MyAbstractMethod");
        }
    }
    
  6. C# sealed keyword and virtual methods

    The sealed keyword is used to prevent further overriding of a virtual method in derived classes. It ensures that a method's implementation cannot be changed beyond a certain point in the inheritance hierarchy.

    public class BaseClass
    {
        public virtual void MyMethod()
        {
            Console.WriteLine("BaseClass MyMethod");
        }
    }
    
    public class DerivedClass : BaseClass
    {
        public sealed override void MyMethod()
        {
            Console.WriteLine("DerivedClass MyMethod");
        }
    }
    
  7. C# virtual property

    Virtual properties work similarly to virtual methods, allowing derived classes to provide their own implementation.

    public class BaseClass
    {
        public virtual string MyProperty { get; set; }
    }
    
    public class DerivedClass : BaseClass
    {
        public override string MyProperty
        {
            get { return "DerivedClass Property"; }
            set { /* Custom implementation */ }
        }
    }
    
  8. When to use the virtual keyword in C#

    Use the virtual keyword when you want to provide a default implementation in the base class that can be optionally overridden by derived classes. This allows for customization and polymorphic behavior.

  9. Inheritance and virtual methods in C#

    Inheritance is a fundamental concept in C#, and virtual methods play a key role. Derived classes inherit the behavior of virtual methods from their base classes but can override them to provide specific implementations.

    public class BaseClass
    {
        public virtual void MyMethod()
        {
            Console.WriteLine("BaseClass MyMethod");
        }
    }
    
    public class DerivedClass : BaseClass
    {
        public override void MyMethod()
        {
            Console.WriteLine("DerivedClass MyMethod");
        }
    }
    
    BaseClass obj = new DerivedClass();
    obj.MyMethod(); // Calls the overridden method in DerivedClass