C# -

Method Overloading

Method overloading in C# allows you to define multiple methods with the same name but different parameters. This feature enhances the flexibility of your code by enabling methods to perform similar operations with different types or numbers of inputs. This tutorial covers various aspects of method overloading, including its definition, use cases, and best practices.


1. Definition of Method Overloading

Method overloading occurs when a class contains multiple methods with the same name but different parameter lists. These differences can be in the number of parameters, the type of parameters, or both. The C# compiler differentiates these methods based on their signatures.

Example:
        
            namespace OverloadingExamples;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Add(3, 5));           // Calls the first Add method
        Console.WriteLine(Add(2.5, 4.3));       // Calls the second Add method
        Console.WriteLine(Add(1, 2, 3));        // Calls the third Add method
    }

    static int Add(int a, int b)
    {
        return a + b;
    }

    static double Add(double a, double b)
    {
        return a + b;
    }

    static int Add(int a, int b, int c)
    {
        return a + b + c;
    }
}
        
    

2. Use Cases for Method Overloading

Method overloading is useful when you want to provide different ways to perform a similar operation. Common use cases include mathematical operations, string manipulations, and initializing objects with different sets of data.

Example:
        
            namespace OverloadingExamples;

class Program
{
    static void Main(string[] args)
    {
        PrintMessage("Hello, World!");
        PrintMessage("Hello, World!", 3);
        PrintMessage("Hello, World!", "John");
    }

    static void PrintMessage(string message)
    {
        Console.WriteLine(message);
    }

    static void PrintMessage(string message, int repeatCount)
    {
        for (int i = 0; i < repeatCount; i++)
        {
            Console.WriteLine(message);
        }
    }

    static void PrintMessage(string message, string name)
    {
        Console.WriteLine($"{message} - From {name}");
    }
}
        
    

3. Best Practices


Conclusion

Method overloading is a powerful feature in C# that enhances code flexibility and readability. By defining multiple methods with the same name but different parameters, you can provide various ways to perform similar operations. This tutorial covered the definition, use cases, and best practices for method overloading.