A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

C# Tutorial 6.3:Method overloading

 

1. Introduction to Method Overloading

Method overloading is a feature in C# that allows a class to have multiple methods with the same name but with different parameters. The compiler determines which method to call based on the number and types of arguments.

2. Basic Syntax

class Example
{
    // Method with no parameters
    public void MyMethod()
    {
        // Method implementation
    }

    // Method with one parameter
    public void MyMethod(int x)
    {
        // Method implementation with one parameter
    }

    // Method with two parameters
    public void MyMethod(int x, string y)
    {
        // Method implementation with two parameters
    }
}

3. Rules for Overloading

  • Methods must have the same name.
  • Methods must be in the same class.
  • Methods must have a different number or type of parameters.
  • The return type does not play a role in method overloading.

4. Example: Overloading with Different Parameter Types

class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

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

5. Example: Overloading with Different Number of Parameters

class Printer
{
    public void Print(string message)
    {
        Console.WriteLine(message);
    }

    public void Print(string message, ConsoleColor color)
    {
        Console.ForegroundColor = color;
        Console.WriteLine(message);
        Console.ResetColor();
    }
}

6. Example: Overloading with Optional Parameters

class Greeter
{
    public void Greet(string name)
    {
        Console.WriteLine($"Hello, {name}!");
    }

    public void Greet(string name, string greeting = "Hello")
    {
        Console.WriteLine($"{greeting}, {name}!");
    }
}

7. Conclusion

Method overloading is a powerful feature in C# that allows you to create more flexible and readable code by defining multiple methods with the same name but different parameters. It's important to follow the rules of overloading to avoid ambiguity and ensure proper functionality.

This tutorial covers the basics of method overloading, including syntax, rules, and examples. Practice using method overloading in your C# projects to enhance code organization and improve code readability.