Menu
Coddy logo textTech

Optional Parameters

Part of the Fundamentals section of Coddy's C# journey — lesson 52 of 69.

In C#, you can define optional parameters in a method by providing a default value in the method signature. This allows you to call the method with or without specifying the argument for that parameter. If the argument is not provided, the default value is used.

Here's the basic syntax for defining an optional parameter:

access_modifier return_type method_name(parameter_type parameter_name = default_value) {
    // Method body
}

For example:

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

In this example, the Greet method has an optional parameter name with a default value of "Guest". You can call this method in two ways:

Greet("Alice"); // Output: Hello, Alice!
Greet(); // Output: Hello, Guest!

If you provide an argument for name, it will be used. If you omit the argument, the default value "Guest" will be used.

Optional parameters must appear after all required parameters in the method signature. You can have multiple optional parameters, but once you define an optional parameter, all subsequent parameters must also be optional.

challenge icon

Challenge

Easy

Create a method named DisplayMessage that takes two parameters:

  1. A required string parameter named message.
  2. An optional integer parameter named repeatCount with a default value of 1.

The method should print the message to the console repeatCount times. If repeatCount is not provided when calling the method, it should default to 1.

Here's an example of how the method will be called:

DisplayMessage("Hello!"); // Prints "Hello!" once
DisplayMessage("Coddy", 3); // Prints "Coddy" three times

Cheat sheet

Optional parameters in C# allow you to define default values in method signatures. If no argument is provided when calling the method, the default value is used.

Basic syntax:

access_modifier return_type method_name(parameter_type parameter_name = default_value) {
    // Method body
}

Example:

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

// Usage:
Greet("Alice"); // Output: Hello, Alice!
Greet(); // Output: Hello, Guest!

Important rules:

  • Optional parameters must appear after all required parameters
  • Once you define an optional parameter, all subsequent parameters must also be optional

Try it yourself

using System;

public class Program {
    // Create the DisplayMessage method here
    

    public static void Main(string[] args) {
        DisplayMessage("Hello!");
        DisplayMessage("Coddy", 3);
    }
}
quiz iconTest yourself

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

All lessons in Fundamentals