Virtual and Override Property in C# - What it is & How to Use (2024)

If you are new to OOP(Object Oriented Programming) and want to know how to use virtual and override property in C#, then congrats, you’ve landed on the right article.🛬

We use a virtual keyword in the base class to modify a property, method, indexer, or event declaration, which is later overridden in a derived class. If you are having a problem understanding this concept, then don’t worry. In this article, we will discuss in detail virtual and override properties.

Before we dive deep into this article, first, let’s discuss the two main concepts Polymorphism and method overriding. So without wasting any time, let’s start moving toward the article.

Table of Contents
  1. What is Polymorphism?
  2. What is Method Overriding?
  3. What is a Property in C#?
  4. What is a Virtual Property in C#?
  5. What is An Override Property in C#?

What is Polymorphism?

One of the main features of OOP(Object Oriented Programming) is polymorphism which means having more than one form. Polymorphism is also expressed as a method that performs different tasks. In inheritance, we inherit different fields and functions from another class, and in polymorphism, we use those functions to perform different operations.

We have two types of polymorphism that are:

  1. Compile-Time Polymorphism.
  2. Run-Time Polymorphism.

Compile-time polymorphism is also known as static polymorphism, and run-time polymorphism is known as dynamic polymorphism. In run-time polymorphism, we have virtual and overriding properties. Run-time polymorphism is implemented by virtual functions. We achieve dynamic polymorphism with the help of method overriding.

What is Method Overriding?

If the same method is available in both base and derived classes. Then, the method in the derived class overrides the method in the base class is known as method overriding. The method overriding is basically the same function performed with different base and derived class operations. We can achieve method overriding with the help of virtual and override keywords.

We use a virtual keyword with a method to tell the compiler this is a method that can be overridden. The virtual keyword is always used with the parent class method, and the override keyword is used with the child class.

Code

//Example of virtual and override keywordsusing System;class parentClass {// Use virtual keyword with print methodpublic virtual void print(){Console.WriteLine("Parent class");}}// class parentClass inherit class childclass child : parentClass{//Use override with the print method of child classpublic override void print(){Console.WriteLine("Child class");}}class mainClass {public static void Main(){parentClass myobj;myobj = new parentClass();// call the print function of parent classobj.print();obj = new child();// call the print function of child classobj.print();}}

Output

Parent classChild class

What is a Property in C#?

We use properties to hide sensitive data from the user; for example, we declare a variable as private, provide its public access through the set and get methods through properties. We can also restrict its value with the help of get and set accessors. A property can be virtual, abstract, or override.

Let’s understand the concept of property with the help of a simple example:

Code

class Student{// private field or variableprivate string Sname;// property to access Snamepublic string StuName{// get method read Snameget { return Sname; }// set method assign value to Snameset { Sname = value; } }}

What is a Virtual Property in C#?

Virtual properties are just like virtual methods. A property with a virtual keyword is called virtual property, which allows the derived class to override it. When we read or write a virtual property through an object reference, the object’s run-time type is used to determine which implementation of the property to use. So now we can write an example in which we declare virtual property:

Code

class Person{// private field or variableprivate string _name;// setting the Person’s Name property as virtual, which can be overriddenpublic virtual string Name{// get method return _name valueget { return _name; }// set method assign value to _nameset { _name = value; } }}

What is An Override Property in C#?

We use the override keyword to override a base class property, which means redefining or modifying the base class virtual property. Now let’s see an example in which we use the above-stated class as a base class which is overridden by our class.

Code

class Student : Person{// private field or variableprivate string _name;private string _lname;// Overriding Name property of person classpublic override string Name{// get method return _name valueget { return _name; }// set method assign value to _nameset { _name = value; } }// Declare a lastName property of type string:public string Code {get {return _lname;}set {_lname= value;} }}

Now let’s understand virtual and override property with the help of a complete example:

Code

using System;class Person{// private field or variableprivate string _name;// setting the Person’s Name property as virtual, which can be overriddenpublic virtual string Name{// get method return _name valueget { return _name; }// set method assign value to _nameset { _name = value; } }// A virtual method to print the value of the name on the screenpublic virtual void Print(){Console.WriteLine("Name:" + Name);}}class Student : Person{// private field or variableprivate string _name;private string _lname;// Overriding Name property of person classpublic override string Name{// get method return _name valueget { return _name; }// set method assign value to _nameset { _name = value; } }// Declare a lastName property of type string:public string Lname {get {return _lname;}set {_lname= value;}}// Override the virtual function of the base classpublic override void Print(){Console.WriteLine("Name:" + Name + " " + Lname);}}class Myclass{static void Main(string[] args){Person bObj = new Person();bObj.Name="Zeshan";bObj.Print();Student dObj = new Student();dObj.Name="Zeshan";dObj.Lname="Afridi";dObj.Print();Console.WriteLine("\nProgram Execute Successfully \n Press Any Key to Exit..");Console.ReadLine();}}

Output

Name: ZeshanName: Zeshan AfridiProgram Execute SuccessfullyPress Any Key to Exit.

Conclusion

To conclude the article on virtual and override property in C#, we have seen that virtual property work like virtual methods. We use virtual and override keywords with property to avail feature of polymorphism.

We write virtual with the property in the base class to which we want to be overridden in the derived class. This article has coded the simplest examples to explain virtual property in detail.

Let’s have a quick review of the topics discussed in this article.

  1. What is polymorphism?
  2. What is method overriding?
  3. What is a property in C#?
  4. What is a virtual property in C#?
  5. What is the override property in C#?

If this article is helpful and solves the mystery of virtual property, don’t forget to share it with your coding partners—also, comment below 👇. Do you understand virtual property?

Happy coding! 🥳

Author

Zeeshan Afridi

Zeeshan is a detail-oriented software engineer and technical content writer with a Bachelor's in Computer Software Engineering and certifications in SEO and content writing. Thus, he has a passion for creating high-quality, SEO-optimized technical content to help companies and individuals document ideas to make their lives easier with software solutions. With over 150 published articles in various niches, including computer sciences and programming languages such as C++, Java, Python, HTML, CSS, and Ruby, he has a proven track record of delivering well-researched and engaging technical content.

Virtual and Override Property in C# - What it is & How to Use (2024)
Top Articles
The Murdaugh trial is over, but infamy lingers for Walterboro
North America Stateside International Talk With Mobile
Tattoo Shops Lansing Il
Cranes For Sale in United States| IronPlanet
Washu Parking
Jackerman Mothers Warmth Part 3
Faint Citrine Lost Ark
Readyset Ochsner.org
Kristine Leahy Spouse
Mlifeinsider Okta
Cvs Devoted Catalog
Morgan Wallen Pnc Park Seating Chart
Gt Transfer Equivalency
Hartford Healthcare Employee Tools
charleston cars & trucks - by owner - craigslist
24 Best Things To Do in Great Yarmouth Norfolk
Bcbs Prefix List Phone Numbers
Define Percosivism
Mission Impossible 7 Showtimes Near Marcus Parkwood Cinema
Tamilyogi Proxy
Sprinkler Lv2
Wbiw Weather Watchers
Tips on How to Make Dutch Friends & Cultural Norms
Rust Belt Revival Auctions
Roane County Arrests Today
Boise Craigslist Cars And Trucks - By Owner
Spiritual Meaning Of Snake Tattoo: Healing And Rebirth!
Sound Of Freedom Showtimes Near Movie Tavern Brookfield Square
Telegram Voyeur
Saxies Lake Worth
Unity Webgl Car Tag
3 Ways to Format a Computer - wikiHow
Possum Exam Fallout 76
Ewg Eucerin
Martins Point Patient Portal
Southtown 101 Menu
Bfri Forum
Indiana Jones 5 Showtimes Near Jamaica Multiplex Cinemas
Manuel Pihakis Obituary
Diana Lolalytics
Scanning the Airwaves
Boone County Sheriff 700 Report
The Conners Season 5 Wiki
Trivago Anaheim California
Brake Pads - The Best Front and Rear Brake Pads for Cars, Trucks & SUVs | AutoZone
Advance Auto.parts Near Me
Hanco*ck County Ms Busted Newspaper
DL381 Delta Air Lines Estado de vuelo Hoy y Historial 2024 | Trip.com
De boeken van Val McDermid op volgorde
Shannon Sharpe Pointing Gif
Pulpo Yonke Houston Tx
Tweedehands camper te koop - camper occasion kopen
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 6078

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.