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
Bones and All | Rotten Tomatoes
The final curtain for the Regal UA, Berkeley’s 90-year-old art deco movie palace
Funny Roblox Id Codes 2023
Golden Abyss - Chapter 5 - Lunar_Angel
Www.paystubportal.com/7-11 Login
Joi Databas
DPhil Research - List of thesis titles
Shs Games 1V1 Lol
Evil Dead Rise Showtimes Near Massena Movieplex
Steamy Afternoon With Handsome Fernando
fltimes.com | Finger Lakes Times
Detroit Lions 50 50
18443168434
Newgate Honda
ZĂĽrich Stadion Letzigrund detailed interactive seating plan with seat & row numbers | Sitzplan Saalplan with Sitzplatz & Reihen Nummerierung
Grace Caroline Deepfake
978-0137606801
Nwi Arrests Lake County
Justified Official Series Trailer
London Ups Store
Committees Of Correspondence | Encyclopedia.com
Pizza Hut In Dinuba
Jinx Chapter 24: Release Date, Spoilers & Where To Read - OtakuKart
How Much You Should Be Tipping For Beauty Services - American Beauty Institute
Free Online Games on CrazyGames | Play Now!
Mccain Agportal
Amih Stocktwits
Fort Mccoy Fire Map
Uta Kinesiology Advising
Kcwi Tv Schedule
What Time Does Walmart Auto Center Open
Nesb Routing Number
Olivia Maeday
Random Bibleizer
10 Best Places to Go and Things to Know for a Trip to the Hickory M...
Black Lion Backpack And Glider Voucher
Gopher Carts Pensacola Beach
Duke University Transcript Request
Lincoln Financial Field, section 110, row 4, home of Philadelphia Eagles, Temple Owls, page 1
Jambus - Definition, Beispiele, Merkmale, Wirkung
Ark Unlock All Skins Command
Craigslist Red Wing Mn
D3 Boards
Jail View Sumter
Birmingham City Schools Clever Login
Thotsbook Com
Funkin' on the Heights
Caesars Rewards Loyalty Program Review [Previously Total Rewards]
Vci Classified Paducah
Www Pig11 Net
Ty Glass Sentenced
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.