Method Overriding in C# - Code Maze (2024)

Posted by Code Maze | Updated Date Nov 8, 2023 | 0

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API programand learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

Method overriding in C# is a form of implementing polymorphism. We also call it “run-time” polymorphism. In this article, we are going to learn more about method overriding, how to implement it, and how it differs from method overloading.

To download the source code for this article, you can visit our GitHub repository.

Let’s begin.

What Is Method Overriding?

When a derived class provides a specific implementation of a method that the base class already defines, we refer to it as “method overriding”.

This allows the subclass to give its own behavior to the method, while still maintaining the same method signature as the base class.

When Do We Need to Override a Method?

When the derived class needs to provide a specialized implementation of a method present in the base class, we need to override the method.

We may need method overriding when:

  • We have a base class with a method that does not perform the desired behavior for the derived class
  • We want to customize the behavior of a method for different subclasses
  • The base class is an abstract class that needs implementation in a derived concrete class.

How to Override a Method?

To override a method in C#, we need to use the override keyword when defining the method in the derived class. The method in the derived class must also have the same name, return type, and parameter list.

We must mark the base method as virtual, or abstract for the derived class to override it.

Override a Virtual Method

Let’s start by creating a base classto understand this:

public class Shape{ public string Color { get; set; } public virtual string Draw() { return $"Drawing a {Color} colored shape"; }}

Here, we have a base class Shape that has a Color property and a Draw() method.The Draw() method is virtual which means we can override it in a derived class.

Now, let’s create a class Circle derived from Shape:

public class Circle : Shape{ public double Radius { get; set; } public override string Draw() { return $"Drawing a {Color} colored circle with a radius of {Radius} units."; }}

And another derived class Square:

public class Square : Shape{ public int Side { get; set; } public override string Draw() { return $"Drawing a square of color {Color} " + $"with its sides having length and width of {Side} units"; }}

Both classes are derived from the Shape class and both override the Draw() method to provide their own implementation.

The Draw() method in the Circle class returns a message that includes the circle’s color and radius, while the Draw() method in the Square class returns a message that includes the square’s color and side length.

Let’s create the instances of these classes and look at the overridden implementation:

var shape = new Shape { Color = "Blue" };Console.WriteLine(shape.Draw());var circle = new Circle { Color = "Red", Radius = 10.5 };Console.WriteLine(circle.Draw());var square = new Square { Color = "Green", Side = 5 };Console.WriteLine(square.Draw());

When we create the instance of Shape class, the base implementation of the Draw() method will be called.

Whereas, the Draw() method is overridden in the Circle and Square class. Hence, the system calls the method implementation in the derived class instead of the base class’s implementation:

Drawing a Blue colored shapeDrawing a Red colored circle with a radius of 10.5 units.Drawing a square of color Green with its sides having length and width of 5 units

One important thing to understand here is that it is not necessary to override a virtual method. If the derived class does not contain an overridden implementation, the instance of the derived class points to the base class implementation of the method.

So, we understood method overriding when the base class method is marked as virtual. Let’s now look at how it differs from overriding an abstract method.

Abstract Method Overriding

The main difference here compared to overriding a virtual method is that an abstract method does not have an implementation of its own. Hence, we must override it in the derived class.

Let’s modify our existing example to understand this:

public abstract class Shape{ public string Color { get; set; } public abstract string Draw();}

Here, the Draw() method is not implemented in the base class and is marked as abstract which means it must be overridden by any derived class. Also, we mark theShape class asabstract.

The Circle and Square classes continue to be derived from the Shape class and override the Draw() method to provide their own implementation.

As the Shape class is now an abstract class, we cannot create an instance of it. So, we need to create an instance of Circle or Square classes and call the Draw() method on it:

var circle = new Circle { Color = "Red", Radius = 5.5 };Console.WriteLine(circle.Draw());var square = new Square { Color = "Blue", Side = 12 };Console.WriteLine(square.Draw());

The output remains similar:

Drawing a Red colored circle with a radius of 5.5 units.Drawing a square of color Blue with its sides having length and width of 12 units

Another important point to understand here is that if a derived class does not override the abstract method, we must mark it as abstract and the process repeats until we reach a class that implements the method.

Access Base Class Method in Overridden Derived Class

It’s common to override methods in a derived class to provide a specific implementation for that class. However, sometimes the derived class may also want to execute the original implementation of the method in the superclass.

C# provides a way to do this using the base keyword.

Let’s extend our example and create another class derived from Shape:

public class Cube : Shape{ public int Edge { get; set; } public override string Draw() { var builder = new StringBuilder(); builder.AppendLine(base.Draw()); builder.AppendLine($"Drawing a cube with edges of length, width, and height of {Edge} units"); return builder.ToString(); }}

Now, the Draw() method in the Cube class first calls the base class’s method using the base keyword and then returns a message that includes the cube’s edge length.

If we create an instance of the Cube class and calling the Draw() method:

var cube = new Cube { Color = "Yellow", Edge = 7 };Console.WriteLine(cube.Draw());

We call the overridden implementation in the derived class along with the base class method.

Drawing a Yellow colored shapeDrawing a cube with edges of length, width, and height of 7 units

The base keyword can be useful in situations where the derived class wants to extend the functionality of the base class method, rather than completely replacing it.

Method Overriding vs Method Overloading in C#

Both method overriding and method overloading are forms of polymorphism in C# that allow a class to have multiple methods with the same name, but with different behaviors.

With method overriding, the derived class provides a specific implementation of a method that the base class already defines. Thus, the subclass gives its own behavior to the method while maintaining the same method signature as the base class.

Whereas with method overloading, we have a class having multiple methods with the same name but different parameter lists. This allows the class to provide different behaviors for the same method based on the parameters passed in.

Conclusion

In this article, we have covered the basics of method overriding, including how to use the override keyword, how to call the base class method from the derived class, and the difference between method overriding and method overloading.

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API programand learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!

Method Overriding in C# - Code Maze (2024)
Top Articles
Vollständiger Leitfaden zur FedEx-Sendungsverfolgungsnummer
Mountain Bike Protective Gear | G-Form Knee & Elbow Guards
The Tribes and Castes of the Central Provinces of India, Volume 3
Northern Counties Soccer Association Nj
Matgyn
Kathleen Hixson Leaked
Unity Stuck Reload Script Assemblies
Mackenzie Rosman Leaked
Robot or human?
Dr Doe's Chemistry Quiz Answer Key
Holly Ranch Aussie Farm
craigslist: south coast jobs, apartments, for sale, services, community, and events
Puretalkusa.com/Amac
Parks in Wien gesperrt
Mivf Mdcalc
Danielle Longet
2021 Lexus IS for sale - Richardson, TX - craigslist
今月のSpotify Japanese Hip Hopベスト作品 -2024/08-|K.EG
Summoner Class Calamity Guide
Operation Cleanup Schedule Fresno Ca
Fool’s Paradise movie review (2023) | Roger Ebert
Accuweather Mold Count
Hdmovie2 Sbs
Mj Nails Derby Ct
Inbanithi Age
The Procurement Acronyms And Abbreviations That You Need To Know Short Forms Used In Procurement
2021 Tesla Model 3 Standard Range Pl electric for sale - Portland, OR - craigslist
Ups Drop Off Newton Ks
49S Results Coral
United E Gift Card
Kempsville Recreation Center Pool Schedule
Foolproof Module 6 Test Answers
Space Marine 2 Error Code 4: Connection Lost [Solved]
Ticketmaster Lion King Chicago
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
MSD Animal Health Hub: Nobivac® Rabies Q & A
Ramsey County Recordease
Jasgotgass2
Live Delta Flight Status - FlightAware
Go Bananas Wareham Ma
Sofia Franklyn Leaks
Craigslist Antique
Brake Pads - The Best Front and Rear Brake Pads for Cars, Trucks & SUVs | AutoZone
Silicone Spray Advance Auto
'The Night Agent' Star Luciane Buchanan's Dating Life Is a Mystery
Timothy Warren Cobb Obituary
Borat: An Iconic Character Who Became More than Just a Film
Nfsd Web Portal
Wieting Funeral Home '' Obituaries
Compete My Workforce
Hkx File Compatibility Check Skyrim/Sse
Basic requirements | UC Admissions
Latest Posts
Article information

Author: Aracelis Kilback

Last Updated:

Views: 6094

Rating: 4.3 / 5 (64 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Aracelis Kilback

Birthday: 1994-11-22

Address: Apt. 895 30151 Green Plain, Lake Mariela, RI 98141

Phone: +5992291857476

Job: Legal Officer

Hobby: LARPing, role-playing games, Slacklining, Reading, Inline skating, Brazilian jiu-jitsu, Dance

Introduction: My name is Aracelis Kilback, I am a nice, gentle, agreeable, joyous, attractive, combative, gifted person who loves writing and wants to share my knowledge and understanding with you.