EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Virtual Keyword in C# 

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » C# Tutorial » Virtual Keyword in C# 

Virtual Keyword in C#

Introduction to Virtual Keyword in C#

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.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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
}

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
}

Popular Course in this category
C# Training Program (6 Courses, 17 Projects)6 Online Courses | 17 Hands-on Project | 89+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.6 (8,847 ratings)
Course Price

View Course

Related Courses
ASP.NET Training (8 Courses, 19 Projects).NET Training Program (4 Courses, 19 Projects)

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());
}
}

Output:

virtual keyword output 1

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());
}
}

Output:

virtual keyword output 2

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.

Recommended Articles

This is a guide to Virtual Keyword in C#. Here we discuss How Virtual Works in C#, Multi-Level Inheritance along with advantages and rules. You may also look at the following article to learn more-

  1. Copy Constructor in C#
  2. Inheritance in C#
  3. C# Functions
  4. C# if Statement
  5. If Statement in Python

C# Training Program (6 Courses, 17 Projects)

6 Online Courses

17 Hands-on Project

89+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C sharp Tutorial
  • Advanced
    • Inheritance in C#
    • Exception Handling in C#
    • Types of Exception in C#
    • C# FileNotFoundException
    • C# NullReferenceException
    • C# OutOfMemoryException
    • C# StackOverflowException
    • Custom Exception in C#
    • What is Multithreading in C#
    • C# finally
    • C# System.IO
    • What is StringBuilder in C#
    • DataReader C#
    • BinaryWriter in C#
    • C# BinaryReader
    • TextWriter in C#
    • TextReader in C#
    • C# StringReader
    • C# StringWriter
    • C# StreamReader
    • C# StreamWriter
    • C# FileInfo
    • What is Design Pattern in C#?
    • Multithreading in C#
    • Sorting in C#
    • Bubble Sort in C#
    • C# SortedList
    • C# SortedSet
    • C# SortedDictionary
    • Abstract Class in C#
    • Access Modifiers in C#
    • C# Generics
    • Deserialization in C#
    • C# Thread
    • C# Thread Join
    • C# Thread Sleep
    • C# Thread Synchronization
    • C# Class
    • Sealed in C#
    • Sealed Class in C#
    • Polymorphism in C#
    • C# Call By Reference
    • Virtual Keyword in C# 
    • Yield Keyword in C#
    • Regular Expression in C#
    • C# Lambda Expression
    • C# Predicate
    • Convert Object to JSON C#
    • Checkbox in C#
    • C# MessageBox
    • Collections in C#
    • List in C#
    • C# LinkedList
    • Listbox in C#
    • Protected in C#
    • C# EventHandler
    • Private in C#
    • this Keyword in C#
    • Static Keyword in C#
    • C# Out Parameter
    • Assert in C#
    • C# Delegates
    • C# Interface
    • Generics in C#
    • Timer in C#
    • C# Serialization
    • Metadata in C#
    • C# Stack
    • C# Using Static
    • Queue in C#
    • C# File.Exists
    • C# Tuples
    • C# Create JSON Object
    • Partial in C#
    • C# readonly
    • C# Action Delegate
    • C# Await Async
    • C# Dictionary
    • IEnumerable C#
    • C# Data Grid View
    • C# Dynamic
    • Web Services in C#
    • C# Pattern Matching
    • C# Extension Methods
    • C# XmlSerializer
  • Basic
    • Uses Of C#
    • C# Versions
    • C# Data Types
    • Variables in C#
    • Namespaces in C#
    • C# Compilers
    • C# Keywords
    • Iterators in C#
    • Objects in C#
    • C# Object Dispose
    • C# object to XML
    • C# check object type
    • C# Object Serialization
    • Pointers in C#
    • C# Literals
    • C# Commands
    • C# Custom Attribute
    • Type Casting in C#
    • String vs String C#
    • C# Struct vs Class
  • Operators
    • Logical Operators in C#
    • Conditional Operators in C#
    • Bitwise Operators in C#
    • C# OR Operator
    • C# Ternary Operators
    • Operator Precedence in C#
  • Control Statement
    • C# if Statement
    • Else If in C#
    • Continue in C#
    • Break in C#
    • Switch Statement in C#
    • Goto Statement in C#
  • Loops
    • C# For Loop
    • C# While Loop
    • C# do-while loop
    • C# foreach Loop
  • Arrays
    • Arrays in C#
    • 2D Arrays in C#
    • C# Jagged Arrays
    • String Array in C#
    • C# Multidimensional Arrays
  • Constructor and Destructor
    • Constructor in C#
    • Copy Constructor in C#
    • Static Constructor in C#
    • Destructor in C#
  • overloading and overrideing
    • Overloading and Overriding in C#
    • Overloading in C#
    • Overriding in C#
    • Method Overloading in C#
    • Method Overriding in C#
    • Operator Overloading in C#
  • Functions
    • C# Functions
    • C# String Functions
    • Math Functions in C#
    • Recursive Function in C#
    • C# Anonymous Functions
    • C# Local Functions
    • Enum in C#
    • Trim() in C#
    • clone() in C#
    • C# random
    • C# String Format()
    • C# String Interpolation
    • C# StartsWith()
    • C# String IndexOf()
    • DateTime in C#
    • C# Nullable
    • C# nameof
    • C# checked
    • C# String PadLeft
    • Convert String to Double in C#
    • Convert int to String C#
    • String to Date C#
    • C# intern()
    • C# Stopwatch
    • C# DirectoryInfo
    • C# Compare()
    • C# Base
    • C# SOAP
    • Lock in C#
  • Programs
    • Patterns in C#
    • Swapping in C#
    • Palindrome in C#
    • Factorial in C#
    • Fibonacci Series in C#
    • Random Number Generator in C#
    • Prime Numbers in C#
    • Armstrong Number in C#
    • Reverse String in C#
  • Interview questions
    • C# Interview Questions and Answers
    • C# OOP Interview Questions
    • C# Design Pattern Interview Questions

Related Courses

C# Certification Training

ASP.NET Course

.NET Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C# Training Program (6 Courses, 17 Projects) Learn More