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
S & W Towing Service (Tucker, GA): Towing | Transportation Breakdown Service Directory
Lady Waks - PinQueue
Great Clips Mount Airy Nc
Artem The Gambler
How To Fix Epson Printer Error Code 0x9e
Canya 7 Drawer Dresser
Froedtert Billing Phone Number
13 Easy Ways to Get Level 99 in Every Skill on RuneScape (F2P)
Unity Stuck Reload Script Assemblies
Did 9Anime Rebrand
Brgeneral Patient Portal
Teenbeautyfitness
Tx Rrc Drilling Permit Query
Stream UFC Videos on Watch ESPN - ESPN
Globe Position Fault Litter Robot
2 Corinthians 6 Nlt
Spider-Man: Across The Spider-Verse Showtimes Near Marcus Bay Park Cinema
Rondom Ajax: ME grijpt in tijdens protest Ajax-fans bij hoofdbureau politie
FDA Approves Arcutis’ ZORYVE® (roflumilast) Topical Foam, 0.3% for the Treatment of Seborrheic Dermatitis in Individuals Aged 9 Years and Older - Arcutis Biotherapeutics
Doublelist Paducah Ky
Sherburne Refuge Bulldogs
Everything To Know About N Scale Model Trains - My Hobby Models
Airline Reception Meaning
Water Temperature Robert Moses
Nk 1399
UCLA Study Abroad | International Education Office
Evil Dead Rise Showtimes Near Sierra Vista Cinemas 16
Shoe Station Store Locator
Korg Forums :: View topic
Christmas Days Away
Account Now Login In
Culver's Hartland Flavor Of The Day
Σινεμά - Τι Ταινίες Παίζουν οι Κινηματογράφοι Σήμερα - Πρόγραμμα 2024 | iathens.gr
Santa Cruz California Craigslist
Wildfangs Springfield
Daily Jail Count - Harrison County Sheriff's Office - Mississippi
Priscilla 2023 Showtimes Near Consolidated Theatres Ward With Titan Luxe
Temu Y2K
Captain Billy's Whiz Bang, Vol 1, No. 11, August, 1920
America's Magazine of Wit, Humor and Filosophy
Indio Mall Eye Doctor
Anguilla Forum Tripadvisor
Oppenheimer Showtimes Near B&B Theatres Liberty Cinema 12
The Wait Odotus 2021 Watch Online Free
Craigslist Antique
Portal Pacjenta LUX MED
Ohio Road Construction Map
Lesson 5 Homework 4.5 Answer Key
Diesel Technician/Mechanic III - Entry Level - transportation - job employment - craigslist
Asisn Massage Near Me
ats: MODIFIED PETERBILT 389 [1.31.X] v update auf 1.48 Trucks Mod für American Truck Simulator
Ranking 134 college football teams after Week 1, from Georgia to Temple
Kindlerso
Latest Posts
Article information

Author: Clemencia Bogisich Ret

Last Updated:

Views: 6086

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.