Virtual Keyword in C# 

WBOY
Release: 2024-09-03 15:26:38
Original
881 people have browsed it

What is the virtual keyword? Before jumping right into C# perspective, it is important to understand or revise the concept of inheritance, overriding and virtual keyword in the object-oriented programming world.

Method Overriding is an OOPs concept closely knit with Inheritance. When a child class method overrides the parent class method of the same name, parameters and return type, it is termed as method overriding. A virtual keyword is an indication to the compiler that a method may be overridden in derived classes.

Coming to the C# perspective, the virtual keyword is used to modify the declaration of any property, method or event to allow overriding in a derived class. In simple terms, the virtual keyword implements the method overriding concept in C#.

Syntax

Any property, method or event can be overridden by adding the virtual keyword in the base class and override keyword in the derived class.

Add the virtual keyword in the base class declaration:

public class Base {
public virtual int abc { get; set; } // this property can be overridden
public virtual void Xyz() { }         // this method can be overridden
}
Copy after login

Add the override keyword in the base class declaration:

public class Derived : Base {
public override int abc { get; set; } // this overrides the base class property
public override void Xyz() { }        // this overrides the base class method
}
Copy after login

How Virtual Works in C#?

The very basic difference between overloading and overriding is that the former is a compile-time mechanism, while the latter comes into play at run time. A virtual keyword comes into action at runtime, thus implementing the method overriding concept.

When any virtual method or property is invoked or accessed, the compiler checks for an overriding member of the method or the property. If one is found, it is invoked. If none is found, the original method or property is invoked.

An excellent question here arises – what happens in the case of multilevel inheritance? Well, if any class member is overridden in more than one level, the deepest overridden member is invoked (the one in the most derived class).

Example

The following example of Virtual Keyword in C#  is mention below

Single-Level Inheritance

Let us take an example to understand the working of a virtual keyword when a single child class inherits the parent class i.e. there is no multilevel inheritance.

Code:

using System;
public class Polynomial
{
public virtual double len
{
get;
set;
}
public virtual double wid
{
get;
set;
}
public virtual double Area()
{
return len * wid;
}
}
public class Rectangle: Polynomial
{
}
public class Square : Polynomial
{
public override double len
{
get;
set;
}
public override double Area()
{
return len * len;
}
}
public class Circle : Polynomial
{
public double radius
{
get;
set;
}
public override double Area()
{
return Math.PI * radius * radius;
}
}
public class Triangle : Polynomial
{
public override double Area()
{
return 0.5 * len * wid;
}
}
public class Program
{
public static void Main()
{
var rect = new Rectangle();
rect.len = 5;
rect.wid = 10;
Console.WriteLine("Area of Rectangle = " + rect.Area());
var sq = new Square();
sq.len = 15;
Console.WriteLine("Area of Square = " + sq.Area());
var cir = new Circle();
cir.radius = 10;
Console.WriteLine("Area of Circle = " + cir.Area());
var tri = new Triangle();
tri.len = 5;
tri.wid = 10;
Console.WriteLine("Area of Triangle = " + tri.Area());
}
}
Copy after login

Output:

Virtual Keyword in C# 

How does the Above Code Work?

In the base class Polynomial, we have declared two properties and one method as virtual. These can now be overridden in child classes. Now we create various child classes of different shapes inheriting the Polynomial class.

In the Rectangle class, we need not override any property or method. The base class implementation would work as-is for the Rectangle class.

In the Square class, we do not have the width property. So we override the length property and the Area method to return the square of the length.

In the Circle class, we neither have length or width. So, we declare a new class-specific property of radius and override the Area method accordingly.

In the Triangle class, we simply override the Area method and the properties are inherited from the base class Polynomial.

When we create objects of the derived classes, the compiler encounters the virtual keyword during the base class construction and thus looks for the overridden members. The overridden members are then invoked accordingly.

Multi-Level Inheritance

Let us modify the above example to include multilevel inheritance.

Code:

using System;
public class Polynomial
{
public virtual double len {       get; set; }
public virtual double wid {       get; set; }
public virtual double Area()
{ return 0; }
}
public class Rectangle : Polynomial
{
public override double Area()
{ return len * wid; }
}
public class Square : Rectangle
{
public override double len { get; set; }
public override double Area()
{ return len * len; }
}
public class Program
{
public static void Main()
{
var rect = new Rectangle();
rect.len = 5;
rect.wid = 10;
Console.WriteLine("Area of Rectangle = " + rect.Area());
var sq = new Square();
sq.len = 15;
Console.WriteLine("Area of Square = " + sq.Area());
}
}
Copy after login

Output:

Virtual Keyword in C# 

Advantages

A virtual member has declarations and definitions in both the base class and derived classes. Virtual members are advantageous when some extra functionalities are required in the derived classes. They serve as add-ons.

Rules

  • A variable cannot be declared virtual. Only properties, methods and events can be declared as virtual.
  • A static member cannot be declared virtual.
  • An abstract member cannot be declared virtual.
  • A private member cannot be declared virtual.
  • A non-virtual member cannot be overridden.
  • The access level, type, and name of both virtual members and the overriding members must be the same. For e.g., if the virtual method is public, overriding method must also be public.

Conclusion

In this article, we understood the concept of virtual in C#. We saw how C# implements the virtual keyword during runtime and looked at the examples.

Virtual members are a great concept of object-oriented programming. However, to gain in-depth knowledge, it is highly recommended to learn about abstract keyword, interfaces, and new keyword. This would greatly help in understanding the difference between them all. This helps in realizing when to use and when not to use virtual.

The above is the detailed content of Virtual Keyword in C# . For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!