TExcelTAD
Home › C# › C# Named & Optional Arguments

C# Named & Optional Arguments

Methods with many parameters can be awkward to call: which true means what, and do you really have to pass every value every time? C# solves this with optional parameters (parameters that have a default value) and named arguments (arguments labelled with the parameter name).

Optional parameters

Give a parameter a default value with = in the declaration. Callers may then leave it out.

csharp · try it yourself
using System;

class Program
{
    static void Greet(string name, string greeting = "Hello", int times = 1)
    {
        for (int i = 0; i < times; i++)
            Console.WriteLine(
quot;{greeting}, {name}!"); } static void Main() { Greet("Sam"); Greet("Sam", "Welcome"); Greet("Sam", "Hi", 2); } }
Hello, Sam!
Welcome, Sam!
Hi, Sam!
Hi, Sam!

Rules for optional parameters:

  • They must come after all required parameters.
  • The default must be a compile-time constant (a literal, const, null, or default).
  • The default is baked into the caller at compile time — changing it in a library requires callers to recompile to see the new value.

Named arguments

A named argument is written as parameterName: value. It makes calls self-documenting and lets you pass arguments in any order.

csharp · try it yourself
using System;

class Program
{
    static void CreateUser(string username, bool isAdmin, bool sendWelcomeEmail)
    {
        Console.WriteLine(
quot;{username}: admin={isAdmin}, email={sendWelcomeEmail}"); } static void Main() { CreateUser("dana", false, true); // what do these mean? CreateUser("erik", isAdmin: true, sendWelcomeEmail: false); // crystal clear CreateUser(sendWelcomeEmail: true, isAdmin: false, username: "fay"); // any order } }
dana: admin=False, email=True
erik: admin=True, email=False
fay: admin=False, email=True

Tip: Use named arguments whenever you pass a bare literal like true, null or 0 whose meaning is not obvious at the call site.

Combining both: skip what you do not need

The real power appears when the two features are combined. With several optional parameters, named arguments let you set only the one you care about and keep the defaults for the rest:

csharp · try it yourself
using System;

class Program
{
    static string FormatPrice(decimal amount, string currency = "EUR", int decimals = 2, bool showSign = false)
    {
        string number = amount.ToString("F" + decimals);
        string sign = showSign && amount > 0 ? "+" : "";
        return 
quot;{sign}{number} {currency}"; } static void Main() { Console.WriteLine(FormatPrice(19.5m)); Console.WriteLine(FormatPrice(19.5m, "USD")); Console.WriteLine(FormatPrice(19.5m, decimals: 0)); Console.WriteLine(FormatPrice(19.5m, showSign: true)); Console.WriteLine(FormatPrice(19.5m, "GBP", showSign: true)); } }
19.50 EUR
19.50 USD
20 EUR
+19.50 EUR
+19.50 GBP

Without named arguments, setting only showSign would force you to repeat "EUR", 2 just to reach the fourth position.

Positional and named together

You can mix positional and named arguments. Positional arguments generally come first; a named argument may appear before positional ones only when it is in its correct position.

csharp · try it yourself
using System;

class Program
{
    static double Box(double width, double height = 1, double depth = 1) => width * height * depth;

    static void Main()
    {
        Console.WriteLine(Box(2));
        Console.WriteLine(Box(2, depth: 5));
        Console.WriteLine(Box(width: 2, height: 3, depth: 4));
    }
}
2
10
24

Quick reference

Call Valid? Why
Box(2) ✔ Defaults used for height and depth
Box(2, depth: 5) ✔ Skips height
Box(depth: 5, width: 2) ✔ All named, any order
Box(depth: 5, 2) ✘ Named out of position followed by positional
Box() ✘ width is required

Optional parameters can sometimes replace a whole family of overloaded methods (next lesson). Use them when the variations differ only in a few default values.

Test yourself

Which declaration is valid?

  1. void F(int a = 1, int b)
  2. void F(int a, int b = 1)
  3. void F(int a = x, int b)
  4. void F(optional int a)

Given void Send(string to, bool urgent = false, int retries = 3), how do you set only retries to 5?

  1. Send("bob", 5)
  2. Send("bob", retries: 5)
  3. Send("bob", , 5)
  4. Send(retries = 5, "bob")