Menu
Coddy logo textTech

Optional Parameters

Part of the Object Oriented Programming section of Coddy's C# journey — lesson 48 of 70.

Optional parameters allow you to define default values for method parameters. When a caller doesn't provide a value for that parameter, the default is used automatically.

You create an optional parameter by assigning a default value in the method signature:

public static void Greet(string name, string greeting = "Hello")
{
    Console.WriteLine(greeting + ", " + name + "!");
}

// Both calls work
Greet("Alice");              // Hello, Alice!
Greet("Bob", "Welcome");     // Welcome, Bob!

Optional parameters must come after all required parameters. You can have multiple optional parameters, and callers can omit any from the right:

public static void CreateUser(string name, int age = 0, bool isActive = true)
{
    Console.WriteLine($"{name}, Age: {age}, Active: {isActive}");
}

CreateUser("Emma");                    // Emma, Age: 0, Active: True
CreateUser("James", 25);               // James, Age: 25, Active: True
CreateUser("Sarah", 30, false);        // Sarah, Age: 30, Active: False

Default values must be compile-time constants - literals, const values, or default expressions. You cannot use variables or method calls as defaults. This makes optional parameters ideal for configuration settings and methods where most callers use common values.

challenge icon

Challenge

Easy

Let's build a notification system that uses optional parameters to provide flexible message formatting. You'll create a utility class that can send notifications with customizable settings, where most callers will use sensible defaults.

You'll organize your code across two files:

  • NotificationService.cs: Create a NotificationService class in the Notifications namespace with a method that demonstrates optional parameters:
    • SendNotification(string message, string priority = "Normal", bool addTimestamp = true) - This method should return a formatted notification string. When addTimestamp is true, prefix the message with [TIMESTAMP]. The format should be: [Priority] Message or [TIMESTAMP] [Priority] Message depending on the timestamp setting.
  • Program.cs: In your main file, demonstrate how optional parameters work by calling SendNotification in three different ways - using all defaults, overriding one parameter, and overriding both optional parameters.

You will receive three inputs:

  • First message (will use all default values)
  • Second message (will use priority "Urgent" with default timestamp)
  • Third message (will use priority "Low" and no timestamp)

Call SendNotification three times and print each result:

  1. First call: pass only the first message (uses defaults: "Normal" priority, timestamp enabled)
  2. Second call: pass the second message with "Urgent" priority (timestamp still defaults to true)
  3. Third call: pass the third message with "Low" priority and false for timestamp

For example, if the inputs are System started, Server overload, and Cache cleared, the output should be:

[TIMESTAMP] [Normal] System started
[TIMESTAMP] [Urgent] Server overload
[Low] Cache cleared

Notice how the same method handles all three scenarios elegantly - callers only specify what they need to change from the defaults!

Cheat sheet

Optional parameters allow you to define default values for method parameters. When a caller doesn't provide a value, the default is used automatically.

Create an optional parameter by assigning a default value in the method signature:

public static void Greet(string name, string greeting = "Hello")
{
    Console.WriteLine(greeting + ", " + name + "!");
}

// Both calls work
Greet("Alice");              // Hello, Alice!
Greet("Bob", "Welcome");     // Welcome, Bob!

Optional parameters must come after all required parameters. You can have multiple optional parameters:

public static void CreateUser(string name, int age = 0, bool isActive = true)
{
    Console.WriteLine($"{name}, Age: {age}, Active: {isActive}");
}

CreateUser("Emma");                    // Emma, Age: 0, Active: True
CreateUser("James", 25);               // James, Age: 25, Active: True
CreateUser("Sarah", 30, false);        // Sarah, Age: 30, Active: False

Default values must be compile-time constants - literals, const values, or default expressions. You cannot use variables or method calls as defaults.

Try it yourself

using System;
using Notifications;

class Program
{
    public static void Main(string[] args)
    {
        // Read the three messages
        string message1 = Console.ReadLine();
        string message2 = Console.ReadLine();
        string message3 = Console.ReadLine();

        // Create an instance of NotificationService
        NotificationService service = new NotificationService();

        // TODO: Call SendNotification three times and print each result:
        // 1. First call: pass only message1 (uses all defaults)
        // 2. Second call: pass message2 with "Urgent" priority (timestamp defaults to true)
        // 3. Third call: pass message3 with "Low" priority and false for timestamp

    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming