C# ยท Chapter 26 of 46

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.

Syntax
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.

Example 1 (csharp)
using System;

class Program {
  static void Greet(string name = "Guest") {
    Console.WriteLine("Hello, " + name);
  }

  static void Main() {
    Greet();
    Greet("Amy");
  }
}
Output
Hello, Guest
Hello, Amy

When no argument is given, the default value "Guest" is used.

Example 2 (csharp)
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));
  }
}
Output
10

params 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.
๐Ÿ’ก Note: Optional parameters must come after all required parameters in the method signature.

๐Ÿ“ Quick Quiz

1. What does an optional parameter have that a required one doesn't?

2. What does the params keyword allow?

3. How many params parameters can a method have?