C#
Beginner
1 min read
Optional Parameters and Named Arguments
Example
// Optional parameters, named arguments, and params
static string BuildEmail(
string to,
string subject,
string body = "",
bool isHtml = false,
string from = "no-reply@example.com",
int priority = 3)
{
string type = isHtml ? "HTML" : "Plain";
return $"From:{from} To:{to} Subject:{subject} Type:{type} Priority:{priority}";
}
// All positional
Console.WriteLine(BuildEmail("alice@example.com", "Hi"));
// Named arguments — skip optional ones in the middle
Console.WriteLine(BuildEmail(
to: "bob@example.com",
subject: "Report",
isHtml: true,
priority: 1));
// params — variable argument count
static int Sum(params int[] numbers)
{
int total = 0;
foreach (int n in numbers) total += n;
return total;
}
Console.WriteLine(Sum(1, 2, 3)); // 6
Console.WriteLine(Sum(10, 20)); // 30
Console.WriteLine(Sum()); // 0
// Combining required, optional, and params
static void Log(string level = "INFO", params string[] messages)
{
foreach (string msg in messages)
Console.WriteLine($"[{level}] {msg}");
}
Log("WARN", "Disk full", "Check storage");
Log(messages: new[] { "Server started" }); // named params array