SyntaxStudy
Sign Up
C# Optional Parameters and Named Arguments
C# Beginner 1 min read

Optional Parameters and Named Arguments

Optional parameters let you define a default value in the method signature. Callers can omit the argument, and the default is used. All optional parameters must come after required parameters. This is a clean way to provide sensible defaults without writing multiple overloads. Named arguments let callers specify which parameter they are providing by name rather than position. This makes call sites more readable for methods with many parameters and allows you to pass only selected optional arguments, skipping the others. The `params` keyword allows a method to accept a variable number of arguments of the same type, collected into an array. It must be the last parameter. `params` is frequently used in logging utilities and test helpers where the number of inputs is not known at compile time.
Example
// Optional parameters, named arguments, and params

static string BuildEmail(
    string to,
    string subject,
    string body           = "",
    bool   isHtml         = false,
    string from           = "no-reply@example.com",
    int    priority       = 3)
{
    string type = isHtml ? "HTML" : "Plain";
    return $"From:{from} To:{to} Subject:{subject} Type:{type} Priority:{priority}";
}

// All positional
Console.WriteLine(BuildEmail("alice@example.com", "Hi"));

// Named arguments — skip optional ones in the middle
Console.WriteLine(BuildEmail(
    to:       "bob@example.com",
    subject:  "Report",
    isHtml:   true,
    priority: 1));

// params — variable argument count
static int Sum(params int[] numbers)
{
    int total = 0;
    foreach (int n in numbers) total += n;
    return total;
}

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

// Combining required, optional, and params
static void Log(string level = "INFO", params string[] messages)
{
    foreach (string msg in messages)
        Console.WriteLine($"[{level}] {msg}");
}

Log("WARN", "Disk full", "Check storage");
Log(messages: new[] { "Server started" });  // named params array