0
0
C Sharp (C#)programming~5 mins

Method overloading in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Method overloading lets you create multiple methods with the same name but different inputs. This helps keep your code simple and organized.

You want to perform similar actions but with different types or numbers of inputs.
You want to make your code easier to read by using the same method name for related tasks.
You need to handle different data types without writing separate method names.
You want to provide flexible ways to call a method depending on what information is available.
Syntax
C Sharp (C#)
returnType MethodName(type1 param1) { ... }
returnType MethodName(type1 param1, type2 param2) { ... }
returnType MethodName(type2 param1) { ... }

Each method must differ by the number or type of parameters.

Return type alone cannot distinguish overloaded methods.

Examples
Two methods named Print handle either an integer or a string.
C Sharp (C#)
void Print(int number) {
    Console.WriteLine($"Number: {number}");
}

void Print(string text) {
    Console.WriteLine($"Text: {text}");
}
Two Add methods add two or three numbers.
C Sharp (C#)
int Add(int a, int b) {
    return a + b;
}

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

This program shows two Display methods. One prints a message once, the other prints it multiple times.

C Sharp (C#)
using System;

class Program {
    static void Display(string message) {
        Console.WriteLine($"Message: {message}");
    }

    static void Display(string message, int times) {
        for (int i = 0; i < times; i++) {
            Console.WriteLine($"Message {i + 1}: {message}");
        }
    }

    static void Main() {
        Display("Hello");
        Display("Hi", 3);
    }
}
OutputSuccess
Important Notes

Method overloading improves code clarity by grouping similar actions under one name.

Be careful to avoid methods that differ only by return type; this causes errors.

Summary

Method overloading means having multiple methods with the same name but different parameters.

It helps write cleaner and easier-to-understand code.

Each overloaded method must differ in parameter type or count.