Method Overloading and Method Overriding in C#

Method Overloading and Method Overriding in C#

23 May 2024
Advanced
6.97K Views
30 min read
Learn via Video Course & by Doing Hands-on Labs

C# Programming For Beginners Free Course

Method Overloading and Method Overriding in C#: An Overview

Method Overloading and Method Overriding are ways to implement compile time and runtime polymorphism in C# respectively. These powerful techniques empower developers to create flexible and efficient code by redefining methods. This article delves into the intricacies of method overloading and method overriding in C#, unraveling the key concepts and best practices concisely.

Method Overloading in C#

Method overloading in C# allows the defining of multiple methods with the same name in the same class but with different parameters. These methods perform similar tasks but can accept different types or numbers of parameters, enabling flexibility and enhancing code readability and reusability.

Why Do We Need Method Overloading in C#?

  • Enhanced Readability: Method names can be more intuitive and descriptive since they don't need to include parameter information, making the code more readable and self-explanatory.
  • Consistency: It provides a consistent way to perform similar operations with different parameter types or counts. Developers can use the same method name regardless of the specific data they are working with.
  • Code Reuse: Overloaded methods can share common functionality, reducing code duplication and promoting code reuse.
  • Flexibility: It offers flexibility for users of the class or library. They can choose the most appropriate method based on their specific needs without having to remember different method names.
  • Polymorphism: Method overloading contributes to the polymorphism concept in object-oriented programming, allowing different implementations of the same method name to be called based on the context.

Important Points to Remember in Method Overloading

  • Different Parameters: Overloaded methods should have different types or numbers of parameters. This enables the compiler to differentiate between them.
  • Return Type: Overloading methods based solely on return type is not allowed. It won't compile because C# does not consider return types when distinguishing between methods.
  • Access Modifiers: Overloaded methods can have different access modifiers (public, private, protected, internal, or protected internal).
  • Static Methods: Methods can be overloaded whether they are static or instance methods.
  • Parameter Data Types: Overloaded methods can differ in the data types of their parameters. For example, one method can accept an int, and another can accept a string.
  • Number of Parameters: Overloaded methods can differ in the number of parameters they accept.
  • Same Method Name: Overloaded methods must have the same name within the same class.

Read More - C Sharp Interview Questions

Different ways of doing overloading methods

Method overloading can be done by changing:

  1. The number of parameters in two methods.
  2. The data types of the parameters of methods.
  3. The Order of the parameters of methods.

Example 1. The number of parameters in the two methods

 // C# program to demonstrate the function overloading by changing the Number of parameters
using System;
class DNT {
// adding two integer values.
public int Add(int a, int b)
{
 int sum = a + b;
 return sum;
}
// adding three integer values.
public int Add(int a, int b, int c)
{
 int sum = a + b + c;
 return sum;
}
// Main Method
public static void Main(String[] args)
{
 // Creating Object
 DNT ob = new DNT();
 int sum1 = ob.Add(1, 2);
 Console.WriteLine("sum of the two "
 + "integer value : " + sum1);
 int sum2 = ob.Add(1, 2, 3);
 Console.WriteLine("sum of the three "
 + "integer value : " + sum2);
}
}

Explanation

This C# program in the C# Compiler demonstrates function overloading by defining two Add methods in the DNT class. One method takes two integer parameters and adds them, while the other takes three integer parameters and calculates their sum. The appropriate method is called based on the number of parameters provided, showcasing the concept of function overloading.

Output

sum of the two integer value : 3
sum of the three integer value : 6

Example 2: The data types of the parameters of methods.

 // C# program to demonstrate the function overloading by changing the Data types of the parameters 
using System;
class DNT {
// adding three integer values.
public int Add(int a, int b, int c)
{
 int sum = a + b + c;
 return sum;
}
// adding three double values.
public double Add(double a,
 double b, double c)
{
 double sum = a + b + c;
 return sum;
}
// Main Method
public static void Main(String[] args)
{
// Creating Object
 DNT ob = new DNT();
int sum2 = ob.Add(1, 2, 3);
Console.WriteLine("sum of the three "
+ "integer value : " + sum2);
double sum3 = ob.Add(1.0, 2.0, 3.0);
Console.WriteLine("sum of the three "
+ "double value : " + sum3);
}
}

Explanation

This C# program demonstrates function overloading by defining two Add methods in the DNT class. One method adds three integers, while the other adds three doubles. The appropriate method is called based on the data types of the provided arguments. The program creates an instance of the DNT class, calls both methods and prints the results for both integer and double additions.

Output

sum of the three integer value : 6
sum of the three double value : 6 

Example 3: The Order of the parameters of methods.

 // C# program to demonstrate the function overloading by changing the Order of the parameters
using System;
class DNT {
// Method
public void Identity(String name, int id)
{
Console.WriteLine("Name1 : " + name + ", "
 + "Id1 : " + id);
}
 // Method
public void Identity(int id, String name)
{
Console.WriteLine("Name2 : " + name + ", "
 + "Id2 : " + id);
}
// Main Method
public static void Main(String[] args)
{
// Creating Object
DNT obj = new DNT();
obj.Identity("Urmi", 1);
obj.Identity(2, "Rumi");
}
}

Explanation

This C# program demonstrates function overloading by defining two Identity methods in the DNT class. One method takes a string followed by an integer as parameters, while the other takes an integer followed by a string. The appropriate method is called based on the order of the provided arguments, showcasing function overloading based on parameter order. When the program is run, it prints the names and IDs in different orders using the overloaded methods.

Output

Name1 : Urmi, Id1 : 1
Name2 : Rumi, Id2 : 2

Method Overriding in C#

In C#, method overriding allows a subclass to provide a specific implementation for a method that is already defined in its superclass. The overridden method in the subclass should have the same name, return type, and parameters as the method in the superclass, enabling polymorphic behavior and facilitating customization in derived classes.

Why do we need a Method Overriding in C#?

  • Polymorphism: Method overriding enables polymorphic behavior, allowing objects of different classes to be treated uniformly through their common base class interface.
  • Flexibility: It provides a way for subclasses to provide specific implementations for inherited methods, tailoring behavior to individual class requirements.
  • Code Reusability: Base class methods can be reused across multiple subclasses, avoiding redundant code and promoting a more efficient development process.
  • Dynamic Binding: Method calls are resolved at runtime, ensuring the appropriate overridden method is invoked based on the object's actual type.
  • Enhances Maintainability: Facilitates easier modifications and extensions to existing code, promoting maintainability and scalability.

Important points to remember:

  • Same Signature: The overriding method in the subclass must have the same name, return type, and parameters as the method in the parent class.
  • Access Modifiers: The access level of the overriding method cannot be more restrictive than the overridden method. It can be the same or more permissive (e.g., public in place of protected).
  • virtual and override Keywords: The base method must be declared as virtual in the parent class and overridden using the override keyword in the child class.
  • Inheritance: Method overriding enables polymorphism, allowing objects of the derived class to be treated as objects of the base class.
  • Runtime Binding: The appropriate method to invoke is determined at runtime based on the actual type of the object, supporting dynamic method resolution.
  • Base Keyword: The base keyword is used in the derived class to explicitly call the overridden method of the base class, allowing further customization while retaining the base class's behavior.
  • Sealed Methods: To prevent further overriding, a method can be marked as sealed in the base class, restricting subclasses from further overriding it.

Types of Keywords for Method Overriding in C#

There are three types of keywords for method overriding in C#

  • Virtual Keywords
  • Override Keyword
  • Base Keyword

Virtual Keyword

In C#, the virtual keyword is used to declare a method, property, or event in a base class that can be overridden by derived classes. When a method is declared as virtual, it means that the method can have an implementation in the base class, but it can also be overridden (redefined) in any derived class.

Example

 using System;

class Animal
{
 // Virtual method
 public virtual void MakeSound()
 {
 Console.WriteLine("The animal makes a generic sound.");
 }
}
class Dog : Animal
{
 // Override the virtual method
 public override void MakeSound()
 {
 Console.WriteLine("The dog barks.");
 }
}
class Cat : Animal
{
 // Override the virtual method
 public override void MakeSound()
 {
 Console.WriteLine("The cat meows.");
 }
}
class Program
{
 static void Main()
 {
 Animal myAnimal = new Animal();
 Animal myDog = new Dog();
 Animal myCat = new Cat();
 myAnimal.MakeSound();
 myDog.MakeSound(); 
 myCat.MakeSound(); 
 }
}

Explanation

In this example, the MakeSound method is declared as virtual in the Animal base class. Both the Dog and Cat classes inherit from Animal and override the MakeSound method with their own implementations. When calling MakeSound on instances of Animal, Dog, or Cat, the appropriate overridden method is executed, demonstrating polymorphism.

Output

The animal makes a generic sound.
The dog barks.
The cat meows.

Override Keyword

In C#, the override keyword is used to indicate that a method, property, indexer, or event in a derived class is intended to override a method, property, indexer, or event in a base class. It provides a way to provide a specific implementation for a virtual or abstract member declared in a base class. When you use the override keyword, you are telling the compiler that you are intentionally overriding a member from the base class.

Example

 using System;

class Shape
{
 public virtual void Draw()
 {
 Console.WriteLine("Drawing a shape");
 }
}

class Circle : Shape
{
 public override void Draw()
 {
 Console.WriteLine("Drawing a circle");
 }
}

class Square : Shape
{
 public override void Draw()
 {
 Console.WriteLine("Drawing a square");
 }
}

class Program
{
 static void Main()
 {
 Shape shape1 = new Circle();
 Shape shape2 = new Square();

 shape1.Draw(); // Output: Drawing a circle
 shape2.Draw(); // Output: Drawing a square
 }
}

Explanation

In this example in the C# Editor, the Shape class has a virtual method called Draw(). The Circle and Square classes inherit from Shape and use the override keyword to provide specific implementations of the Draw() method. When creating objects of Circle and Square classes and calling the Draw() method through the base class reference, the overridden methods in the respective derived classes are invoked, demonstrating polymorphic behaviour in C#.

Output

Drawing a circle
Drawing a square

Base Keyword

This is how derived classes can access members of the base class. Basically, it was used to access the base class' constructors, methods, and functions. A static method cannot utilize the basic keyword. The base keyword indicates which base class's constructor should be used for creating instances of the derived class.

Example

 // C# program to show the use of 'base' keyword in method overriding
using System;

// base class
public class web {
string name = "DotNetTricks";

// 'showdata()' is member method,
// declare as virtual
public virtual void showdata()
{
 Console.WriteLine("Website Name: " + name);
}
}
// derived class
// class 'web' is inherits
// class 'stream'
class stream : web {
string s = "Computer Science";
 
//'showdata()' is overridden
// in derived class
public override void showdata()
{
 
 // Calling 'showdata()' of base
 // class using 'base' keyword
 base.showdata();
 Console.WriteLine("About: " + s);
}
}
class DNT {
 
// Main Method
static void Main()
{
 // 'E' is object of class stream
 // also works as object of 
 // class 'web'
 stream E = new stream();
 // it first invokes 'showdata()'
 // of class 'web' then it invokes 
 // 'showdata()' of class 'stream'
 E.showdata(); 
}
}

Explanation

This C# program demonstrates method overriding using the base keyword. A base class web has a method showdata(), and a derived class stream overrides it. The base.showdata() call inside the derived class invokes the base class method before extending functionality, displaying both base and derived class outputs.

Output

Website Name: DotNetTricks 
About: Computer Science
Conclusion

In C#, method overloading, and method overriding are powerful techniques that enhance code flexibility and reusability. Method overloading enables defining multiple methods with the same name but different parameters, enhancing versatility. Method overriding allows customizing inherited methods, promoting polymorphism and dynamic behavior. Mastering these concepts is essential for effective object-oriented programming in C#.

Take our Csharp skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Angular Certification Course Jun 16 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jun 17 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
ASP.NET Core Certification Training Jun 17 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
.NET Microservices Certification Training Jun 23 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
ASP.NET Core (Project) Jun 23 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Azure Developer Certification Training Jun 23 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
React JS Certification Training | Best React Training Course Jun 30 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
ASP.NET Core Certification Training Jun 30 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jun 30 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Generative AI For Software Developers Jul 14 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this