C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Method Parameters

C# Method Parameters

C# provides flexible ways to pass data into methods — positional, named, optional, ref, out, and params.

1 - Default / Optional Parameters

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

Greet("Alice");            // Hello, Alice!
Greet("Bob", "Hi");        // Hi, Bob!

2 - Named Arguments

public static void CreateUser(string name, int age, string role = "user")
{
    Console.WriteLine($"{name}, {age}, {role}");
}

CreateUser(age: 25, name: "Alice", role: "admin");

3 - ref and out Parameters

// ref — pass by reference (must be initialised)
public static void Double(ref int value)
{
    value *= 2;
}
int x = 5;
Double(ref x);
Console.WriteLine(x); // 10

// out — pass by reference (need not be initialised)
public static bool TryParse(string s, out int result)
{
    return int.TryParse(s, out result);
}
if (TryParse("42", out int n))
    Console.WriteLine(n); // 42

4 - params Array

public static int Sum(params int[] numbers)
{
    return numbers.Sum();
}

Console.WriteLine(Sum(1, 2, 3));        // 6
Console.WriteLine(Sum(10, 20, 30, 40)); // 100

Note: Use out parameters when a method needs to return multiple values — for example the TryParse pattern used throughout the .NET base class library.

-Tip-