C# Parameters & Optional Args
Methods can accept parameters, which are values passed in when the method is called. C# also supports optional parameters with default values, and named arguments for clarity.
The `params` keyword lets a method accept a variable number of arguments as an array, which is useful when you don't know in advance how many values will be passed.
static void Method(type param = defaultValue) { }
static void Method(params type[] values) { }Optional parameters
A parameter can have a default value, making it optional when calling the method, like `static void Greet(string name = "Guest")`. If omitted, the default value is used.
Named arguments and params
Named arguments let you specify which parameter a value belongs to regardless of order, like `Greet(name: "Amy")`. The `params` keyword allows a method to accept any number of arguments.
using System;
class Program {
static void Greet(string name = "Guest") {
Console.WriteLine("Hello, " + name);
}
static void Main() {
Greet();
Greet("Amy");
}
}Hello, Guest
Hello, AmyWhen no argument is given, the default value "Guest" is used.
using System;
class Program {
static int Sum(params int[] numbers) {
int total = 0;
foreach (int n in numbers) total += n;
return total;
}
static void Main() {
Console.WriteLine(Sum(1, 2, 3, 4));
}
}10params lets Sum() accept any number of int arguments as an array.
Key points
- Optional parameters have a default value and can be omitted.
- Named arguments specify parameters by name, regardless of order.
- The params keyword accepts a variable number of arguments.
- Only one params parameter is allowed, and it must be last.
