Optional Parameters
In this page:
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
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: