Tracks
/
C#
C#
/
Syllabus
/
Optional Parameters
Op

Optional Parameters in C#

3 exercises

About Optional Parameters

A method parameter can be made optional by assigning it a default value. When a parameter is optional, the caller is not required to supply an argument for that parameter, in which case the default value will be used. Optional parameters must be at the end of the parameter list; they cannot be followed by non-optional parameters. If a method has multiple optional parameters, you can specify only some of them using named arguments.

class Card
{
    static string NewYear(int year = 2020, string sender = "me")
    {
        return $"Happy {year} from {sender}!";
    }
}

Card.NewYear();     // => "Happy 2020 from me!"
Card.NewYear(1999); // => "Happy 1999 from me!"
Card.NewYear(sender: "mom"); // => "Happy 2020 from mom!"

An optional parameter's value must be either:

  • A constant expression (e.g. "hi", 2, DayOfWeek.Friday, null etc.)
  • A new expression of a value type
  • A default expression of a value type
Edit via GitHub The link opens in a new window or tab

Learn Optional Parameters

Practicing is locked

Unlock 2 more exercises to practice Optional Parameters