CodeBlanks Logo Icon CodeBlanks

Default parameters

C# course · Beginner · Lesson 78/116

Learn to define parameters with default values.

Default parameters

A parameter can be given a default value; this is called a default parameter. The declaration adds = value to the parameter: static void Greet(string name = "Friend"). If no argument is given at the call, this value is used.

For example, Greet() uses "Friend" for name; Greet("Ayşe") uses the given argument. Default parameters add flexibility at the call site.

Default and ordering

Default parameters must come at the end of the parameter list. A parameter without a default cannot follow one with a default. Doing so gives a compile error.

At the call site, parameters with defaults can be skipped. The call CheckAge(20) on the definition static void CheckAge(int age, int limit = 18) uses the default 18 for limit.

Exercise Age limit check

Define a static void CheckAge(int age, int limit = 18) method. In the body write Console.WriteLine(age >= limit). In Main, call CheckAge(20) (use the default for limit).

Show example solution
Add Console.WriteLine(age >= limit); to the CheckAge body, write CheckAge(20); in Main.
Example solution:
using System;

class Program
{
    static void CheckAge(int age, int limit = 18)
    {
        // Print the result of age >= limit
        Console.WriteLine(age >= limit);
    }

    static void Main()
    {
        // Call CheckAge
        CheckAge(20);
    }
}

Test yourself

  1. What does Greet() print?

    static void Greet(string name = "Friend")
    {
        Console.WriteLine("Hello, " + name);
    }
    Greet();
    • Hello, Friend
    • Hello,
    • Hello, name
    • Empty
    Show answer

    Hello, Friend — Correct. No argument was passed, so name = "Friend" is used.

  2. Match each expression to its meaning

    name = "Friend"
    Default value
    Greet()
    Uses default
    Greet("Ayşe")
    Passes argument
    static void
    No return value
  3. Default parameter

    static void Greet(string name ____)
    {
        Console.WriteLine(name);
    }
    Show answer
    static void Greet(string name = "Friend")
    {
        Console.WriteLine(name);
    }

All lessons in Beginner