Understanding C# Methods: Method Parameters and Method Overloading

Spread the love

Methods are frequently used in any application. The method is also known as function. It reduces code redundancy and allows code reusability. In this blog, we will explore What are methods, method parameters and method overloading. 

What Are Methods in C#?

A method in C# is a block of code that performs a specific task. Methods help you avoid code repetition by encapsulating commonly used code in one place. Once a method is defined, it can be called multiple times throughout your program.

Here’s a simple example of a method in C#:

public class Program
{
    static void Main(string[] args)
    {
        Welcome(); // Calling the method
    }

    static void Welcome()
    {
        Console.WriteLine("Hello, welcome to learning C#!");
    }
}

In this example, Welcome() is a method that prints a message to the console. Whenever you call the Welcome() method, the message will appear.

Method Parameters in C#

The above example shows a method without parameters but in the real world methods often require method parameters. Method parameters allow you to pass data into methods. They act as placeholders for values that the method will use when executed. Parameters are defined inside the parentheses of the method declaration.

Let’s understand with an example:

public class Program
{
    static void Main(string[] args)
    {
        GetUser("Smith", 37); // Passing arguments to the method
    }

    static void GetUser(string name, int age)
    {
        Console.WriteLine($"Name -  {name}");
        Console.WriteLine($"Age - {age}");

    }
}

Breakdown:

  • Parameters: In this case, GetUser takes two parameters: a string name and an int age.
  • Arguments: When calling the method, you pass values (or arguments) that correspond to these parameters. In this case, we passed “Smith” and 37.

Types of Method Parameters

1) Value Parameters:

The most common type, where values are passed to the method. The method works with a copy of the data, so changes inside the method do not affect the original data.

Example:

public class Program
{
 	static void Main(string[] args)
    	{
        		MultiplyNumber(5,7);
    	}

	static void MultiplyNumber(int a, int b)
	{
		int multiply = a * b;
		Console.WriteLine(multiply); // Output: 6
	}
}

2) Reference Parameters (ref):

These allow you to pass a reference to the original data. Changes made to the parameter inside the method will affect the original variable.

Example:

public class Program
{
	static void Main(string[] args)
	{
		int num= 5;
		AddNumber(ref num);
		Console.WriteLine(num); // Output: 6
	}

	static void AddNumber(ref int number)
	{
		number = number + 1; 
	}
}

3) Output Parameters (out):

Similar to ref, but the variable doesn’t need to be initialized before being passed. The method must assign a value to the out parameter before it exits.

Example:

public class Program
{
    static void Main(string[] args)
    {
    	   int i;      
           Addition(out i);
	   // Display the value i
	   Console.WriteLine( i); // Output: 15
    }

    static void Addition(out int i)
    {
         i = 10;
         i += 5;
    }
}

4) Optional Parameters:

C# allows you to define default values for parameters, making them optional. If you don’t pass a value when calling the method, the default value will be used.

Example:

public class Program
{
	static void Main(string[] args)
        {
		PrintMessage(); // Output: Hello World
    	        PrintMessage("Hi there!"); // Output: Hi there!
	 }
}

static void PrintMessage(string message = "Hello World")
{
    Console.WriteLine(message);
}

Method Overloading in C#

Method overloading allows you to define multiple methods with the same name but different parameters. This makes your code more flexible, as the same method name can be used to perform different tasks depending on the number or type of arguments passed.

Why Use Method Overloading?

Instead of creating several methods with similar functionality but different names, method overloading allows you to keep the method names consistent while varying their input parameters. This improves readability and makes your code easier to maintain.

Example:

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

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

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

class Program
{
    static void Main(string[] args)
    {
        Calculator calc = new Calculator();
        
        Console.WriteLine(calc.Add(5, 10));           // Calls Add(int, int)
        Console.WriteLine(calc.Add(20.3, 25.7));       // Calls Add(double, double)
        Console.WriteLine(calc.Add(5, 15, 15));       // Calls Add(int, int, int)
    }
}

The Add method is overloaded three times:

  1. Add(int, int) adds two integers.
  2. Add(double, double) adds two double values.
  3. Add(int, int, int) adds three integers.

Depending on the type and number of arguments you pass when calling the method, the appropriate overloaded version is executed. This makes your code adaptable to different types of data without needing to invent new method names.

Rules for Method Overloading

When overloading methods in C#, you must follow these rules:

  • Methods must differ in the number of parameters, the type of parameters, or both.
  • Methods cannot differ only in their return type.

For example, these would be valid overloads:

void DisplayDetail(string message) { /* Your code */ }
void DisplayDetail(string message, int times) { /* Your code */ }
void DisplayDetail(int number) { /* Your code */ }

However, these would not be valid overloads because they only differ in return type:

int Add() { /* Your code */ }
double Add() { /* Your code */ } // Invalid, must differ in parameters

Mastering method parameters and method overloading will help you write cleaner, more efficient, and more adaptable code as you grow as a C# developer.


Spread the love