← Back to C# Course | Chapter 5: Methods | Lesson 5 of 6

Optional Parameters

An optional parameter has a built-in backup answer, like a burger that comes with cheese unless you say otherwise. Callers may leave it out and the default is used.

In this page:

  1. Optional Parameters
Syntax
csharp
static void MethodName(type required, type optional = defaultValue)
{
    // body
}

MethodName(a);      // uses the default
MethodName(a, b);   // overrides it

Optional Parameters

A parameter becomes optional by giving it a default value in the method declaration, letting callers omit it entirely. Optional parameters must come after all required parameters.

Named arguments let you skip earlier optional parameters and set a later one directly.

Warning: Optional parameter defaults are baked in at the call site's compile time, not the method's — be careful if you change a default later without recompiling callers.

Example: Optional Parameters

markup
using System;

class Program
{
    static void Greet(string name, string greeting = "Hello")
    {
        Console.WriteLine($"{greeting}, {name}!");
    }

    static void Main(string[] args)
    {
        Greet("Priya");
        Greet("Priya", "Welcome");
        Greet(name: "Lee", greeting: "Hi");
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Putting an optional parameter before a required one, which is a compile error.
  2. Using a non-constant default value, which must be a compile-time constant.
  3. Changing a default value in a library and expecting old callers to pick it up without recompiling.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.