OOP (object oriented programming)What is the class?What do you mean by object?What are the differences between class and object?Can you create an object without using new operator in C#?What is constructor and how many constructors can have one class?Differences between constructor and method of the class? What is default constructor?What is parameterized Constructor in C#?What is private constructor: In what instances you will declare a constructor to be private?What is static constructor, Is it possible to have a static constructor in class. If yes why we need to have a static constructor?Does C# provide copy constructor for an object? How do you call the multiple constructors of a class with single object creation?What is constructor chaining in C#?Can a constructor be called directly from a method?What is constructor overloading and how it’s different than method overloading?What is the difference between constructor overloading and method overloading?Is it possible to overload copy constructor in C#?Can we overload static constructors in C#?Can we overload private constructors in C#?Can we give return type of the constructor in C#?What is the destructor and when it’s called?Is it possible to call constructor and destructor explicitly?What is the Structure and why we need it although we have a class?What are the similarities between Class and Structure?What is the difference between Class and Structure?What is copy structure?What is nested structure?Is it always necessary to create an object of the class?How many different ways to create an object of the class?What are the pros and cons of creating object by new() keyword?What are the pros and cons of delegate object creation to DI container?What are the pros and cons of creating an object by reflection?What are the pros and cons of getting an object from an object pool?What are the pros and cons of creating an object by deserialization?Is it possible to create an object without a class in C#?What is constant?What is static modifier? What are the Static fields and methodsWhat is Static ReadOnly?What are the limitations of static?What is readonly? What’s the difference between constant and read-only?What is this keyword?What is base keyword?What is the difference between this and base keyword?Can “this” keyword be used within static method?What are the accessors?What is the static class? Why we need of static class?If someone wants to create static class then what are the rules for the static class?What are the limitations of using static keyword?What are finalizers in c#?How to create N number of instances of C# class?What are the Nested Classes and why we use them?What are the basic four pillars of OOP?What is the Inheritance and why we need of inheritance?How do you inherit a class into other class in C#?What is the concept of base and derive class?What are the different types of inheritance?We have two classes’ base class and child class. A is the base class and B is the child class, If we create an instance of child class then which class’s constructor called first?Does a derived class can inherit the constructors of its base class?What should we do that if we create an object of child class then the parameterized constructor of base class must be invoked?As we know that base constructor invoked first when we create instance of child class but if we create an instance of child class by parameterized constructor and base class has both default and parameterized constructor then which constructor of the base will be invoked?Can you assign an object of derived class to the variable of base class and if both have the same method name then which will be invoked?Can we create instance of base class and store it to derive class?Can we create derive class object inside base class, and if create instance of child class then what will happen?Can we inherit child class from 2 base classes? if yes then how? If not then why?Does C# support Multiple Inheritance?Why multiple inheritance is not supported in C# and why it’s supported in C++?How is multiple inheritance achieved in C#?What are Access Modifiers? Explain private, public, protected, internal, protected internal access modifiersWhat are the default access modifiers of the class?Why classes cannot be declared as protected?Can we declare private class in namespace?What are the valid access specifier used for the declaration of class at namespace level? If we inherit a class, do the private variables also get inherited?Can you prevent your class from being inherited?Can you prevent your class from being inherited without using sealed keyword?What is abstraction?What is encapsulation?What is the difference between abstraction and encapsulation?What is polymorphism?What is static or compile time polymorphism?What is runtime polymorphism or late binding or dynamic binding?What is method overloading?When and why we should use overload methods?What is inheritance based overloading?What are the advantages of using overloading?Can we overload the method in the same class?What is the execution control flow in overloaded methods?What is method overriding?What s virtual keyword?What are the key points to make the method as overridden?When it is must to override the method?When a derived class can overrides the base class member?Can we declare fields inside the class as virtual?When we treat sub-class method as an overriding method?Can we override private virtual method in c#?Can we override method in the same class?Can we execute parent class method if it is overridden in the child class?If we have virtual in base class and the same method is overridden in child class, by creating instance of child class and assign it to base class, then which of the method will be invoked first.What is the difference between method overloading and method overriding?What is method hiding?Can you access a hidden method in the derived which is declared in the base class?What is the difference between method overriding and method hiding?You have a component with 2 parameters and deployed to client side, now you have changed your method with 3 parameters, how can you deploy this without affecting the client code?What is operator overloading?What is abstract class and why we need of it?What are the rules of abstract classes?What is an abstract method?What is concrete method?When do you use abstract class in C#?When to use the abstract method in C#?

What is Method Overloading in C#? Explained with Examples

Short Answer

Method overloading is a feature in programming where multiple methods in the same class share the same name but have different parameter lists. This allows you to call the same method name with different types or numbers of arguments. The correct method to execute is determined at compile time based on the arguments you pass.

Detailed Explanation with Examples

What is Method Overloading?

Method overloading is a way to define multiple methods with the same name in a class, but with different parameters. This makes your code more flexible and easier to use because you can call the same method name for different purposes, depending on the input.

For example, imagine you have a Calculator class. You might want to add two integers, two decimals, or even concatenate two strings. Instead of creating separate method names like AddIntegers, AddDecimals, and ConcatenateStrings, you can use the same method name, Add, for all of them. The compiler will figure out which version of Add to use based on the arguments you provide.

Why is Method Overloading Useful?

Method overloading is useful because:

  • Improved Readability: Using the same method name for similar tasks makes your code easier to understand.
  • Flexibility: You can handle different types of inputs without creating separate method names.
  • Code Reusability: You can reuse the same method name for different scenarios, reducing code duplication.

How to Perform Method Overloading in C#

There are two main ways to overload methods in C#:

  1. Changing the Number of Parameters:
    • You can create methods with the same name but a different number of parameters.
    • Example:
      
      int Add(int a, int b) { return a + b; }
      int Add(int a, int b, int c) { return a + b + c; }
      			
  2. Changing the Data Type of Parameters:
    • You can create methods with the same name but different parameter types.
    • Example:
      
      int Add(int a, int b) { return a + b; }
      double Add(double a, double b) { return a + b; }
      				

Real-Time Example: A Simple Calculator

Let’s look at a practical example of method overloading using a Calculator class in C#.

Step 1: Define the Calculator Class

Here’s a Calculator class with three overloaded Add methods:


using System;

class Calculator
{
    // Method to add two integers
    public int Add(int a, int b)
    {
        return a + b;
    }

    // Method to add two doubles
    public double Add(double a, double b)
    {
        return a + b;
    }

    // Method to concatenate two strings
    public string Add(string a, string b)
    {
        return a + b;
    }
}

Step 2: Use the Overloaded Methods

In the Main method, we create an instance of the Calculator class and call the Add method with different types of arguments.


class Program
{
    static void Main(string[] args)
    {
        Calculator calculator = new Calculator();

        // Call the Add method with integers
        int result1 = calculator.Add(5, 10);

        // Call the Add method with doubles
        double result2 = calculator.Add(3.5, 2.8);

        // Call the Add method with strings
        string result3 = calculator.Add("Hello, ", "world!");

        // Display the results
        Console.WriteLine("Result 1: " + result1);
        Console.WriteLine("Result 2: " + result2);
        Console.WriteLine("Result 3: " + result3);
    }
}

Step 3: Observe the Output

When you run the program, you’ll see the following output:

Result 1: 15
Result 2: 6.3
Result 3: Hello, world!

In this example:

  • The first Add method adds two integers (5 and 10) and returns 15.
  • The second Add method adds two doubles (3.5 and 2.8) and returns 6.3.
  • The third Add method concatenates two strings ("Hello, " and "world!") and returns "Hello, world!".

Key Points to Remember About Method Overloading

  • Same Method Name: Overloaded methods must have the same name.
  • Different Parameters: The parameter lists must differ in either the number or type of parameters.
  • Compile-Time Resolution: The correct method is chosen at compile time based on the arguments passed.
  • Return Type Doesn’t Matter: Overloading is not determined by the return type. Only the parameter list matters.
  • Access Modifiers: Overloaded methods can have different access modifiers (e.g., public, private), but they must have the same name and compatible parameter lists.
  • Improves Readability: Overloading makes code more intuitive by using the same method name for similar tasks.
  • Common Use Cases:
    • Mathematical operations (e.g., adding integers, doubles, etc.).
    • Constructors with different parameter sets.
    • Type conversions (e.g., ToString methods).

Common Mistakes to Avoid

  • Changing Only the Return Type:
    • Overloading is not achieved by just changing the return type. The parameter list must differ.
    • Example (Invalid):
      
      int Add(int a, int b) { return a + b; }
      double Add(int a, int b) { return a + b; } // Error: Same parameter list
      			
  • Too Many Overloads:
    • Avoid creating too many overloaded methods, as it can make your code harder to understand.
  • Poor Naming:
    • Ensure the method name clearly describes its purpose, even when overloaded.

Real-World Use Case: Constructors

Method overloading is commonly used in constructors. For example, you might have a Person class with multiple constructors to initialize objects in different ways:


class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    // Constructor with no parameters
    public Person()
    {
        Name = "Unknown";
        Age = 0;
    }

    // Constructor with name parameter
    public Person(string name)
    {
        Name = name;
        Age = 0;
    }

    // Constructor with name and age parameters
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}
	

Final Thoughts

Method overloading is a powerful feature in C# that allows you to write cleaner, more intuitive code. By using the same method name for different tasks, you can make your code easier to read and maintain. Whether you’re working on a simple calculator or a complex application, method overloading is a tool you’ll use often in your programming journey.