C# Method Overloading

In C# programming, method overloading is a fundamental object-oriented programming principle that permits the declaration of multiple methods within a class using the same identifier but different parameters. This feature enables the implementation of various versions of the same operation, offering flexibility based on the input types or quantities. The selection of the suitable method for execution is determined by the parameters passed during the function call, enhancing code adaptability across diverse input situations while maintaining a single method name.

Syntax:

It has the following syntax:

Example

class Class_Name

{

    // Method 1

    return_Type MethodName(parameter_list1) {

        // method body

    }

    //method 2

    return_Type MethodName(parameter_list2) {

        // method body

    }

}

In this code structure, we've included two function definitions sharing identical names but with varying parameters.

For Example:

Example

int method(int a)

float method (float a)

double method (double a, double b)

Method Overloading Example in C#

Let's consider an example to demonstrate method overloading in C#.

Example

Example

using System;



class Calculator

{

    // Method 1 - multiply two integers

    public int Mul(int x, int y)

    {

        return x * y;

    }



    // Method 2 - multiply three integers

    public int Mul(int x, int y, int z)

    {

        return x * y * z;

    }



    // Method 3 - multiply two double numbers

    public double Mul(double x, double y)

    {

        return x * y;

    }

}



class C# Tutorial

{

    static void Main()

    {

        Calculator calc = new Calculator();



        Console.WriteLine("Multiplications of 2 ints: " + calc.Mul(15, 10));

        Console.WriteLine("Multiplications of 3 ints: " + calc.Mul(4, 6, 5));

        Console.WriteLine("Multiplications of 2 doubles: " + calc.Mul(6.5, 4.8));

    }

}

Output:

Output

Multiplications of 2 ints: 150

Multiplications of 3 ints: 120

Multiplications of 2 doubles: 31.2

Explanation:

In this instance, we are showcasing a Mul function named differently for handling various parameter combinations such as two integers, three integers, and two doubles. During compilation, the method to be executed is determined based on the specific arguments provided.

Important points for Method Overloading

There are several important points for method overloading in C#. Some of them are as follows:

  • Overloaded methods are distinguished based on the number and parameter types that are passed as arguments to the methods.
  • If we have taken multiple methods with the same parameter but different return types, it will throw a compile-time error.
  • We cannot define multiple methods with the same name, and the type of the arguments, it will throw a compile-time error.
  • It can have different access modifiers , such as public and private.
  • All overloaded methods should have the same name within the same class.
  • Different ways to perform Method Overloading in C#

In the C# programming language , method overloading improves code readability by combining related operations into a single and descriptive label. It encourages reusability by reducing duplication and avoiding several names for similar functionality. It enables flexibility by allowing the same method name to handle a variety of input types or numbers.

We can perform method overloading in C# in three ways:

  • By changing the number of parameters
  • By changing the data type of the arguments
  • Using different data types for parameters

Here, we will explore various techniques that can be utilized to implement method overloading in C#.

1. By changing the number of Parameters

In C# programming, method overloading is accomplished by creating several methods with identical names but varying parameter counts. The compiler determines the correct method to execute depending on the quantity of arguments passed in the method invocation.

Syntax:

It has the following syntax:

Example

returnType MethodName(type1 param1, type2 param2)  // Overloaded Method with 2 parameters

returnType MethodName(type1 param1, type2 param2, type3 param3)  // Overloaded method with 3 parameters

In this C# tutorial, we will explore an example of method overloading by altering the number of parameters in the methods.

Consider the following example to understand how method overloading works when the number of parameters is changed:

  1. Create a class with multiple methods having the same name but a different number of parameters.
  2. Demonstrate how C# allows us to define multiple methods with the same name as long as the number of parameters or the types of parameters are different.
  3. Show how method overloading enables us to call different methods based on the number of arguments provided.

By following this example, you can gain a better understanding of method overloading in C# by adjusting the number of parameters.

Let's consider an example to demonstrate method overloading by altering the quantity of parameters in C#.

Example

Example

using System;  

    public class Cal

     {    

        public static int add(int x, int y)

     {  

            return x + y;  

        }  

        public static int add(int x, int y, int z)  

        {  

            return x + y + z;  

        }  

    }  

    public class TestMemberOverloading  

    {  

        public static void Main()  

        {  

            Console.WriteLine(Cal.add(12, 23));  

            Console.WriteLine(Cal.add(12, 23, 25));  

        }  

    }

Output:

Output

35

60

Explanation:

In this instance, we are showcasing the Cal class containing two add functions: one accepting two integer arguments and the other accepting three integer arguments. Subsequently, the compiler selects the appropriate method based on the number of arguments provided during the function call.

2) By Changing the Data Type of the Arguments

In C#, method overloading occurs when you define multiple methods sharing the same name but with varying parameter data types. This differentiation can be based on either the number of parameters or the specific data types of those parameters.

Syntax:

It has the following syntax:

Example

returnType MethodName(int param1, int param2)    // Method with int parameters

returnType MethodName(double param1, double param2) // Overloaded method with double parameters

In this C# example, we demonstrate method overloading by altering the data type of the arguments passed to the method.

Let's consider an example to demonstrate method overloading by altering the data type of the parameters in C#.

Example

Example

using System;  

    public class Cal

{  

        public static int add(int a, int b)

{  

            return a + b;  

        }  

        public static float add(float a, float b)  

        {  

            return a + b;  

        }  

    }  

    public class TestMemberOverloading  

    {  

        public static void Main()  

        {  

            Console.WriteLine(Cal.add(12, 23));  

            Console.WriteLine(Cal.add(12.4f,21.3f));  

        }  

    }

Output:

Output

35

33.7

Explanation:

In this instance, we are examining a Cal class with a pair of add functions, one designed for whole numbers and the other for decimal values. Subsequently, the parameter data types are employed to determine the appropriate function to execute.

3) Using Different Data Types for Parameters

Method overloading is accomplished by creating several methods that share the same name but have different parameter types or a different number of parameters.

Syntax:

It has the following syntax:

Example

// Method with int and double parameters

    returnType MethodName(int parameter1, double parameter2)

    // Overloaded method with double and string parameters

    returnType MethodName(double parameter1, string parameter2)

    // Overloaded method with string and int parameters

    returnType MethodName(string parameter1, int parameter2)

In this C# tutorial, we will demonstrate method overloading by utilizing various data types for parameters.

Let's consider a scenario to demonstrate method overloading in C# by employing various data types for parameters.

Example

Example

using System;

class ProductDetails 

{

    public void Print(string productName, double price)

    {

        Console.WriteLine("The Product Name is: " + productName + "\nThe Price is: " + price);

    }

    public void Print(double price, string productName)

    {

        Console.WriteLine("The Product Name is: " + productName + "\nThe Price is: " + price);

    }

    public static void Main(string[] args)

    {

        ProductDetails p = new ProductDetails();

        p.Print("Laptop", 58000.75);

        p.Print(1500.50, "Headphones");

    }

}

Output:

Output

The Product Name is: Laptop

The Price is: 58000.75

The Product Name is: Headphones

The Price is: 1500.5

Explanation:

In this instance, we are examining the ProductDetails class which includes a pair of Print functions: one receiving a string first and then a double, while the other takes a double first and then a string. The selection of which function to use is based on the sequence and data type of the arguments supplied.

Constructor Method Overloading

In C#, constructor overloading permits the creation of multiple constructors within a single class using identical names but varying parameters. This feature enables the initialization of class instances using distinct approaches depending on the input parameters.

Syntax:

It has the following syntax:

Example

class ClassName

{

    // Default constructor (no parameters)

    public ClassName()

    {

        // body of the code

    }



    // Parameterized constructor (with parameters

    public ClassName(type1 par1, type2 par2)

    {

        // body of the code

    }

}

Constructor Method Overloading Example in C#

Let's consider a scenario to demonstrate the concept of constructor overloading in C#.

Example

Example

using System;



class Employee

{

    private int empId;

    private string name;

    private string depart;



    // Constructor 1 - Default

    public Employee()

    {

        empId = 0;

        name = "None";

        depart = "General";

    }



    // Constructor 2 - Initialize with ID and Name

    public Employee(int id, string empName)

    {

        empId = id;

        name = empName;

        depart = "General";

    }



    // Constructor 3 - Initialize with ID, Name, and Department

    public Employee(int id, string empName, string dept)

    {

        empId = id;

        name = empName;

        depart = dept;

    }



    public void Show()

    {

        Console.WriteLine($"Employee ID: {empId}, Employee Name: {name}, Employee Department: {depart}");

    }

}



class consOverloading

{

    static void Main()

    {

        // Using different constructors

        Employee emp1 = new Employee();  // default constructor

        Employee emp2 = new Employee(101, "Michael");  // constructor with 2 params

        Employee emp3 = new Employee(102, "Johnson", "HR");  // constructor with 3 params



        emp1.Show();

        emp2.Show();

        emp3.Show();

    }

}

Output:

Output

Employee ID: 0, Employee Name: None, Employee Department: General

Employee ID: 101, Employee Name: Michael, Employee Department: General

Employee ID: 102, Employee Name: Johnson, Employee Department: HR

Explanation:

In this instance, we are examining an Employee class with 3 attributes: a default constructor, a second parameter for setting the empid and employee name, and a third parameter for initializing all fields. Subsequently, the appropriate constructor is invoked to instantiate the employee objects based on the provided arguments.

Conclusion

In summary, C# method overloading allows for the creation of multiple methods sharing the same name but with varying parameter lists. This feature offers a form of compile-time polymorphism that improves the clarity, reusability, and adaptability of code. By leveraging method overloading, developers can manage related tasks using a single method name, leading to more organized and maintainable code.

Method Overloading FAQs

1) What is method overloading in C#?

In C#, method overloading is the practice of creating multiple methods with identical names but different parameter lists within a single class.

No, method overloading cannot be accomplished solely by changing the return type.

No, achieving method overloading is not possible simply by altering the return type of a method while keeping the same parameter list intact.

3) What are a few typical methods for method overloading?

We have the ability to overload a function by modifying the quantity of parameters, data types, or their order.

The decision on which overloaded method to call is determined at compile time based on the number and types of parameters in the method signature.

In C#, the selection of the specific overloaded method to execute is determined during compile-time, taking into account the quantity, data type, and sequence of parameters supplied to the method.

5) Can constructors be overloaded in C#?

Yes, constructors are capable of being overloaded with varying parameter lists.

Input Required

This code uses input(). Please provide values below: