Function overloading in C# allows you to create multiple methods with the same name, differentiated by their parameters. This leads to cleaner code and enhances the readability of your applications. Below are three practical examples demonstrating how to implement and utilize method overloading in C#.
This example showcases how to calculate the area for different shapes using method overloading. The same method name CalculateArea
is used, but with varying parameters to handle circles and rectangles.
public class AreaCalculator
{
// Method to calculate the area of a circle
public double CalculateArea(double radius)
{
return Math.PI * radius * radius;
}
// Method to calculate the area of a rectangle
public double CalculateArea(double length, double width)
{
return length * width;
}
}
// Usage
AreaCalculator calculator = new AreaCalculator();
double circleArea = calculator.CalculateArea(5); // Area of circle
double rectangleArea = calculator.CalculateArea(4, 6); // Area of rectangle
CalculateArea
is overloaded to accept different parameters based on the shape being calculated.In this example, we demonstrate a Print
method that can handle different types of input, such as strings and integers. This illustrates how function overloading can simplify output operations.
public class Printer
{
// Method to print a string
public void Print(string message)
{
Console.WriteLine("String: " + message);
}
// Method to print an integer
public void Print(int number)
{
Console.WriteLine("Integer: " + number);
}
}
// Usage
Printer printer = new Printer();
printer.Print("Hello, World!"); // Prints string
printer.Print(42); // Prints integer
In this example, we illustrate how to process data in different ways based on the input type. We overload a method called ProcessData
to handle arrays of integers and lists of strings.
using System.Collections.Generic;
public class DataProcessor
{
// Method to process an array of integers
public void ProcessData(int[] numbers)
{
foreach (var number in numbers)
{
Console.WriteLine("Processing integer: " + number);
}
}
// Method to process a list of strings
public void ProcessData(List<string> strings)
{
foreach (var str in strings)
{
Console.WriteLine("Processing string: " + str);
}
}
}
// Usage
DataProcessor processor = new DataProcessor();
processor.ProcessData(new int[] { 1, 2, 3 }); // Processes integers
processor.ProcessData(new List<string> { "apple", "banana" }); // Processes strings