Skip to content

Methods

Methods are blocks of code that contain a series of statements. They are used to perform specific tasks and can be reused throughout your program. Methods help organize code into manageable chunks and promote code reuse.

Method Declaration

A method declaration consists of a return type, name, parameters (if any), and a body containing the code to be executed. Methods can be public, private, or protected, determining their accessibility.

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

Parameter Types

Parameters allow you to pass data into methods. C# supports various parameter types to handle different scenarios and requirements.

csharp
// Optional parameters
public void Greet(string name = "World")
{
    Console.WriteLine($"Hello, {name}!");
}

// Reference parameters
public void Swap(ref int a, ref int b)
{
    int temp = a;
    a = b;
    b = temp;
}

// Output parameters
public void Divide(int x, int y, out int quotient, out int remainder)
{
    quotient = x / y;
    remainder = x % y;
}

Method Overloading

Method overloading allows you to define multiple methods with the same name but different parameter lists. This enables you to provide different ways of calling a method based on the arguments passed.

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

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