C# is a powerful object-oriented programming language developed by Microsoft as part of the .NET ecosystem. One of the most important features of object-oriented programming (OOP) is polymorphism. In C#, polymorphism is primarily achieved using the virtual and override keywords. These keywords allow derived classes to provide specific implementations of methods that are already defined in a base class.
Understanding the C# virtual keyword and C# override keyword is essential for mastering runtime polymorphism in C#, designing extensible applications, and writing maintainable enterprise-level code. In this detailed tutorial, we will explore how virtual and override work, how method overriding differs from method hiding, practical examples, best practices, and real-world use cases.
Polymorphism means βmany forms.β In C#, polymorphism allows objects of different classes to be treated as objects of a common base class. There are two types of polymorphism:
The virtual and override keywords in C# are used to achieve runtime polymorphism. Runtime polymorphism allows a method call to be resolved at runtime rather than compile time.
The virtual keyword in C# is used to declare a method, property, indexer, or event in a base class that can be overridden in a derived class.
When a method is marked as virtual, it allows derived classes to provide a different implementation of that method.
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal makes a sound.");
}
}
Here, the MakeSound() method is marked as virtual. This means child classes can override it.
The override keyword in C# is used in a derived class to provide a new implementation of a virtual method defined in the base class.
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Dog barks.");
}
}
Here, the Dog class overrides the virtual method from the Animal class.
Let us see a full example demonstrating method overriding in C#.
using System;
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal makes a sound.");
}
}
public class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Cat meows.");
}
}
public class Program
{
public static void Main()
{
Animal myAnimal = new Cat();
myAnimal.MakeSound();
}
}
Cat meows.
Even though the reference type is Animal, the runtime object is Cat. Therefore, the overridden method is called. This demonstrates runtime polymorphism in C#.
| Virtual | Override |
|---|---|
| Declared in base class | Declared in derived class |
| Allows method to be overridden | Provides new implementation |
| Enables polymorphism | Implements polymorphism |
| Optional in base class | Mandatory in derived class when overriding |
Method hiding uses the new keyword.
public class Animal
{
public void MakeSound()
{
Console.WriteLine("Animal sound.");
}
}
public class Dog : Animal
{
public new void MakeSound()
{
Console.WriteLine("Dog bark.");
}
}
Method hiding does not support runtime polymorphism. It resolves at compile time.
Sometimes you may want to call the base class implementation inside an overridden method.
public class Dog : Animal
{
public override void MakeSound()
{
base.MakeSound();
Console.WriteLine("Dog barks loudly.");
}
}
The base keyword allows access to base class members.
Not only methods, but properties can also be virtual.
public class Shape
{
public virtual double Area
{
get { return 0; }
}
}
public class Circle : Shape
{
private double radius;
public Circle(double r)
{
radius = r;
}
public override double Area
{
get { return 3.14 * radius * radius; }
}
}
If you want to prevent further overriding in derived classes, use sealed override.
public class Dog : Animal
{
public sealed override void MakeSound()
{
Console.WriteLine("Dog bark.");
}
}
Now no further derived class can override this method.
A base Payment class can define a virtual method ProcessPayment(). Different payment methods override it.
Base logger class defines virtual Log(). Derived classes customize logging behavior.
Base Character class defines virtual Attack(). Different characters override it.
Derived class cannot override the method using override.
No, static methods cannot be virtual or overridden.
No, constructors cannot be virtual.
No, only if method is abstract.
Virtual method calls involve dynamic dispatch. While the performance overhead is minimal in modern .NET applications, excessive use of virtual methods may slightly impact performance in highly optimized systems.
The C# virtual and override keywords are fundamental to achieving runtime polymorphism. Virtual enables a method to be overridden, while override provides a new implementation in a derived class. Together, they form the backbone of inheritance in C# and object-oriented programming in C#.
Mastering method overriding in C# allows developers to build scalable, flexible, and maintainable software applications. Whether you're preparing for a C# interview, learning .NET development, or building enterprise applications, understanding virtual and override is essential.
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved