An Introduction to Method Overriding - Virtual, Override And New Keywords in C# explained (2024)

The use of inheritance and polymorphism has become an integral part of our life as a programmer. Inheritance provides a lot of benefits including code reusability, separation of concerns, cleaner code, extensibility etc.

Polymorphism is one of the three main concepts of object-oriented programming, the other two being Encapsulation and Inheritance. Polymorphism is frequently used with inheritance. By polymorphism here, I mean run-time polymorphism or method overriding. Compile time polymorphism or method overloading does not require inheritance.

We are going to discuss method overriding here with some examples.

Method overriding is a feature that allows an object of a base class to call the methods (with the same name, parameters, and return type) of a base class as well as derived class based on the instance of the class it holds.

Note: Referencetype assignments in C# work with Covariant mode, so you cannot assign the instance of a base class to a derived class object.

For example - I have a base class Fruit with the function Details(). There is another class Mango which inherits Fruit but also has a function named Details().

publicclassFruit{publicvoidDetails(){-----------}-----------}publicclassMango:Fruit{publicvoidDetails(){-----------}-----------}

Through overriding, an object of Fruit can call Details() of Fruit, if it stores the instance of Fruit. object of Fruit can call the method- Details of class Mango, if it stores the instance of class Mango.

Fruita=newFruit();a.Details();// Should call themethod-DetailsofbaseclassFruita=newMango();a.Details();// Should callthemethod-DetailsofderivedclassMango

Ok, so we learned what is overriding.

But practically, to achieve this, we may need to use a couple of keywords and we are going to check them out.

These keywords are – virtual, override, and new.

Virtual and Override

We use these two keywords to achieve the overriding functionality mentioned above. We can have a better understanding if we do it with some samples.

Open Visual Studio, go to File -> New -> Project -> Console App, and name it as OverridingSample.

An Introduction to Method Overriding - Virtual, Override And New Keywords in C# explained (1)

I have added a class named Inheritance to the project. Open the Overriding.cs and remove the default class in it.

Add two classes named Base and Derived, as below.

publicclassBase{publicBase(){}}publicclassDerived:Base{publicDerived(){}}

The derived class inherits from the Base class. Then, add a method Function1() to the Base class as below.

publicvoidFunction1(){}

Add the same method to the Derived class as well.

You can notice one thing that the compiler raises warning that it hides the Base.Function1() and if that is intended, you can add a new keyword.

An Introduction to Method Overriding - Virtual, Override And New Keywords in C# explained (2)

You can build the project. You will see that despite having this compiler warning, the project gets compiled successfully. To test how this works, I created a class called TestOverriding and added the code as mentioned below.

//Withoutusingvirtul,overrideandnewpublicvoidTest1(){Baseb=newBase();b.Function1();Derivedd=newDerived();d.Function1();Basebd=newDerived();bd.Function1();//Doesn'tworkasperoverridingprinciple}

I have declared three objects,

  • The first one is of type Base and holds an instance of Base class.
  • The second one is of type Derived and holds an instance of a Derived class.
  • The third one is of type Base and holds an instance of the Derived class.

Now, create an object of the TestOverriding class in the Program.cs and call the method Function1().

TestOverridingoverriding=newTestOverriding();overriding.Test1();

It will create the following output.

An Introduction to Method Overriding - Virtual, Override And New Keywords in C# explained (3)

While the first two function calls work as expected, the third function call doesn’t work as expected as per the overriding principle.

As per overriding principle, though bd was of type Base, when it is initialized with object Derived, it should have invoked the method of the Derived class.

Here comes the role of override keyword.

If we add the virtual keyword before the base class method and override keyword before the derived class method, we can solve the above problem. I am going to create a new method called Function2 to demonstrate how override keyword works.

Add the below method to the base class.

virtualpublicvoidFunction2(){Console.WriteLine("Base-Function2");}

Also, add the below code to the derived class.

overridepublicvoidFunction2(){Console.WriteLine("Derived-Function2");}

Note that you can add virtual and override keywords either before or after the public keyword.

Test2() looks like below.

//Usesvirtualinbaseclassandusedoverrideinderivedclass.publicvoidTest2(){Baseb=newBase();b.Function2();Derivedd=newDerived();d.Function2();//WatchthisouttocheckifoverridingworksBasebd=newDerived();bd.Function2();//Thisworksasexpected}

Call the method Test2(),

overriding.Test2();

and here is the output.

An Introduction to Method Overriding - Virtual, Override And New Keywords in C# explained (4)

Now, we can see thatall the scenarios work as expected especially, the third which works as per the overriding principle.

Now, we can check what happens if I remove virtual or override from the two methods in the base and derived classes.

Base class method declared as virtual and derived class declared without overriding

First, I am going to remove the override keyword from the derived class while keeping the virtual in the base class.

Base class method

virtualpublicvoidFunction2(){Console.WriteLine("Base-Function2");}

Derived class method

publicvoidFunction2(){Console.WriteLine("Derived-Function2");}

I am getting a compile time warning here but the contents here contain two suggestions instead of one, in case of Test1().

An Introduction to Method Overriding - Virtual, Override And New Keywords in C# explained (5)

The warning first suggests using override keyword, mainly because of the fact that we have defined the base class as virtual. The compiler is smart enough to assume that you may have missed adding override keyword in the derived class.

But the result, if we run the above code, is same as that of the Test1().

An Introduction to Method Overriding - Virtual, Override And New Keywords in C# explained (6)

Base class method note declared as virtual and derived class declared as overriding

Now, add the override back to the derived class method and remove virtual from the base class.

The functions should look like this.

Base class method

publicvoidFunction2(){Console.WriteLine("Base-Function2");}

Derived class method

overridepublicvoidFunction2(){Console.WriteLine("Derived-Function2");}

Here, you have the compiler error shown which is obvious.

An Introduction to Method Overriding - Virtual, Override And New Keywords in C# explained (7)

Take away

  1. For overriding to work as expected, you should declare the base class as virtual and use override keyword in the derived class to override it.
  2. Virtual and override work together to get the desired result and you cannot override a class which is not marked as virtual.
  3. Declaring the base class as virtual and not decorating the derived class with override keyword means you are notoverriding the method.

A little advanced scenario

Since we have learned the basics, now we can try a more realistic scenario.

I am going to add a method named Show in base class. Unlike other methods we have created so far, I am not going to write the overridden method in the derived class.

//AllobjectscallthesamemethodinbaseclasswhichcallsotheroverriddenmethodspublicvoidTest3(){Baseb=newBase();b.Show();Derivedd=newDerived();d.Show();//WatchthisouttocheckifoverridingworksBasebd=newDerived();bd.Show();//Thisworksasexpected}

I am going to call the same Show() using 3 different objects in Test3(),

overriding.Test3();

Here you have the output:

An Introduction to Method Overriding - Virtual, Override And New Keywords in C# explained (8)

The first scenario, which base type object and base type instance behaves very normally. We are calling the Show method of base class and which in turn calls the base class methods, Function1 and Function2.

But in the case of second method call, which has type of derived and instance of derived, it is worth checking the Function1().

Here also we calling the Show() of base class which in turn calls the Function1() and Function2(). Since we have not declared the Function1() as virtual and used override in derived class, the base class method, Show() cannot call the derived calls Function1(). On the other hand, since Function2() is defined as virtual and overridden in derived class, Show() is able to call the Function2() of derived class.

Third example, works exactly like second, since the object holds the instance of derived class itself.

Override keyword is not only used with virtual, it is also used with abstract.

If a base class declares a method as abstract, the method need to be defined in the derived class using override keyword.

New Keyword

Adding new keyword to a method tells that you are aware that the method hides the base class method.

Remember, in Test1() we have seen that when we use the same method name in derived class and does not use override keyword, we will get a compiler warning: “Derived class method … hides the base class method …., if the hiding was intended, use new keyword.”.

New keyword suppresses the warning in shown in Test1() but doesn’t change anything in the output.

Let us create a new method and write a test method for this.

Add the below method to our base class,

publicvoidFunction3(){Console.WriteLine("Base-Function3");}

Then add the below method to our derived class,

newpublicvoidFunction3(){Console.WriteLine("Derived-Function3");}

You can see that new keyword is added before the Fucntion3().

Just like virtual and override, you can add the new keyword before or after the public keyword.

New keyword suppresses the warning.

Let’s create a test method now,

//Usesnewinderivedclassandnotusedvirtualinbaseclass.publicvoidTest4(){Baseb=newBase();b.Function3();Derivedd=newDerived();d.Function3();Basebd=newDerived();bd.Function3();}

Call the test method,

overriding.Test4();

and here is the output

An Introduction to Method Overriding - Virtual, Override And New Keywords in C# explained (9)

We can see that the output is like the output of Test1() where we neither used virtual nor new.

Only difference is new suppresses the warning and we are making sure we know that the method is not overridden.

We cannot use override and new to qualify the same method because they are mutually exclusive in nature.

Though object bd contains instance of Derived class, since we have mentioned the Function3() as new, it cannot access the Function3() of Derived class. This is because, it takes overriding to call the method of derived class when the object holds the instance of derived class. By using new, we have clearly mentioned that we are not using overriding here instead it is a new method with the same name.

Hope you understood the use of virtual, override and new keywords and what is overriding in c#.

You can download and use the attached source code to play with it further.

An Introduction to Method Overriding - Virtual, Override And New Keywords in C# explained (2024)

FAQs

An Introduction to Method Overriding - Virtual, Override And New Keywords in C# explained? ›

In C#, a method in a derived class can have the same name as a method in the base class. You can specify how the methods interact by using the new and override keywords. The override modifier extends the base class virtual method, and the new modifier hides an accessible base class method.

What are virtual override and new keywords in C#? ›

The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class. The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or base class event into a derived class.

What is the definition of method overriding in C#? ›

override (C# reference)

An override method provides a new implementation of the method inherited from a base class. The method that is overridden by an override declaration is known as the overridden base method. An override method must have the same signature as the overridden base method.

Can we override a method without a virtual keyword in C#? ›

The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member. By default, methods are non-virtual. You cannot override a non-virtual method.

What is the new keyword for methods in C#? ›

The new keyword is used to indicate that a method or property in a derived class is intended to hide, rather than override, a method or property in the base class. In this example, the Draw() method in the Circle class is marked as new.

What does virtual keyword mean in C#? ›

The 'virtual' keyword in C# lights up the green signal for a method, property or indexer to be overridden in a derived class. It's like playing catch – the base class 'throws' the 'virtual' method, and the derived class 'catches' it to create an overridden form.

What is the difference between overriding and overloading in C#? ›

Overloading is determined at compile time and is static. Overriding is determined at runtime and is dynamic. Overloading concerns giving a method with the same name different parameters. Overriding concerns defining a different implementation of the same method in inherited classes.

What is method overriding in simple words? ›

Conclusion. In Java, method overriding occurs when a subclass (child class) has the same method as the parent class. In other words, method overriding occurs when a subclass provides a particular implementation of a method declared by one of its parent classes.

How to avoid method overriding in C#? ›

To prevent being overridden, use the sealed in C#. When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method.

What is the difference between overloading and overriding? ›

When the method signature (name and parameters) are the same in the superclass and the child class, it's called overriding. When two or more methods in the same class have the same name but different parameters, it's called overloading.

What is the difference between virtual and non virtual methods in C#? ›

When the method is declared as virtual in a base class, and the same definition exists in a derived class, there is no need for override, but a different definition will only work if the method is overridden in the derived class. Two important rules: By default, methods are non-virtual, and they cannot be overridden.

Can you override a virtual method? ›

Unlike an abstract method, a virtual method is optional. You can provide code in a base-class, and optionally override it.

Is override keyword necessary in C#? ›

Since the method is declared abstract in its parent class it doesn't have any implementation in the parent class, so why is the keyword override necessary here? Because if you don't put it there, you are "hiding" the method instead of overriding it.

What is the difference between virtual override and new keywords? ›

The override modifier extends the base class virtual method, and the new modifier hides an accessible base class method. The difference is illustrated in the examples in this topic. In a console application, declare the following two classes, BaseClass and DerivedClass .

What is a new keyword in C#? ›

The new Keyword in C# has two uses. It can be used as a modifier that explicitly hides a member that is inherited from a base class or as an operator to create a new instance of a type.

What is overriding in C#? ›

If derived class defines same method as defined in its base class, it is known as method overriding in C#. It is used to achieve runtime polymorphism. It enables you to provide specific implementation of the method which is already provided by its base class.

What does the new keyword do in C#? ›

The new operator creates a new instance of a type.

What is the difference between static and virtual keyword in C#? ›

A static property cannot be marked as abstract. Of course, a class derived from C must also implement I and have a method M(). The keyword "virtual" is used to mark a member of a class to allow it to be overridden in a derived class. By default, methods are non-virtual and cannot be overridden.

What is abstract override vs virtual override C#? ›

In C#, virtual methods can be overridden in derived classes, while abstract methods must be overridden in derived classes. This allows for flexible behavior and enables polymorphism in object-oriented programming. These two concepts allow for flexibility and reusability in object-oriented programming.

Top Articles
PC/Mac Patch Notes v10.0.5 | Gold Road & Update 42
Gabourey Sidibe, Kristen Welker, Ayesha Curry, more celebrities who welcomed babies in 2024
Varsity Competition Results 2022
These Walls Have Eyes Walkthrough - The Casting of Frank Stone Guide - IGN
Craigslist The Big Island
Nail Salons Open Now Near My Location
Does Shell Gas Station Sell Pregnancy Tests
Vacature Ergotherapeut voor de opname- en behandelafdeling Psychosenzorg Brugge; Vzw gezondheidszorg bermhertigheid jesu
Temu Beanies
Vivek Flowers Chantilly
Gopher Hockey Forum
Calvert Er Wait Time
Dryers At Abc Warehouse
10000 Divided By 5
Pa Pdmp Log In
Tammi Light Obituary
Stone Eater Bike Park
Comcast Business Sign In
Claims Adjuster: Definition, Job Duties, How To Become One
Brise Stocktwits
Brake Masters 208
The Athenaeum's Fan Fiction Archive & Forum
Westgate Trailer Mountain Grove
Cavender’s 50th Anniversary: How the Cavender Family Built — and Continues to Grow — a Western Wear Empire Using Common Sense values
Anon Rotten Tomatoes
Peak Gastroenterology Associates Briargate
Theater X Orange Heights Florida
Craigs List Plattsburgh Ny
Funny Shooter Unblocked
Andrew Camarata Castle Google Maps
Tri-State Dog Racing Results
Shiftwizard Login Wakemed
Denise Frazier Leak
Sweeterthanolives
Kayak Parts Amazon
Erfahrungen mit Rheumaklinik Bad Aibling, Reha-Klinik, Bayern
Imperialism Flocabulary Quiz Answers
Voyeur Mature Bikini
Psalm 136 Nkjv
Best Turntables of 2023 - Futurism
Let's Take a Look Inside the 2024 Hyundai Elantra - Kelley Blue Book
Ewing Irrigation Prd
Barbarian Frenzy Build with the Horde of the Ninety Savages set (Patch 2.7.7 / Season 32)
Uw Oshkosh Wrestling
Left Periprosthetic Femur Fracture Icd 10
Brokaw 24 Hour Fitness
Roblox Mod Menu Platinmods
Workspace.emory.og
Rubrankings Austin
Mt Sinai Walk In Clinic
Nordstrom Rack Glendale Photos
Craigslist Org Sd Ca
Latest Posts
Article information

Author: Tish Haag

Last Updated:

Views: 6100

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Tish Haag

Birthday: 1999-11-18

Address: 30256 Tara Expressway, Kutchburgh, VT 92892-0078

Phone: +4215847628708

Job: Internal Consulting Engineer

Hobby: Roller skating, Roller skating, Kayaking, Flying, Graffiti, Ghost hunting, scrapbook

Introduction: My name is Tish Haag, I am a excited, delightful, curious, beautiful, agreeable, enchanting, fancy person who loves writing and wants to share my knowledge and understanding with you.