C# provides flexible ways to pass data into methods — positional, named, optional, ref, out, and params.
public static void Greet(string name, string greeting = "Hello")
{
Console.WriteLine($"{greeting}, {name}!");
}
Greet("Alice"); // Hello, Alice!
Greet("Bob", "Hi"); // Hi, Bob!
public static void CreateUser(string name, int age, string role = "user")
{
Console.WriteLine($"{name}, {age}, {role}");
}
CreateUser(age: 25, name: "Alice", role: "admin");
// 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
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