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:
Syntax
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
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");
}
}
Login to try C/C++/Java/PHP code in the editor
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
- Putting an optional parameter before a required one, which is a compile error.
- Using a non-constant default value, which must be a compile-time constant.
- 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: