C#•Methods
C# Named and Optional Parameters in Method Definitions
C# allows method parameters to define default constant values, making them optional for callers. When invoking methods, named arguments (parameterName: value) allow arguments to be passed in any order while dramatically improving readability and eliminating ambiguous boolean flags.
Syntax
public static void ConfigureServer(string host, int port = 8080, bool enableSsl = true) { ... }
// Invocation
ConfigureServer("api.compilra.dev", enableSsl: false);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| Optional Parameters | Feature | Parameters with default values (e.g. int port = 8080) that callers can omit. |
| Named Arguments | Feature | Specifying parameterName: value allows passing arguments in any arbitrary order. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C# locally:
using System;
public class Program {
// Method with required parameters and multiple optional parameters
public static void DeployCluster(
string clusterId,
int nodeCount = 3,
string region = "us-east-1",
bool autoScaling = true,
int maxRetries = 5
) {
Console.WriteLine($"Cluster: {clusterId}");
Console.WriteLine($"Nodes: {nodeCount}");
Console.WriteLine($"Region: {region}");
Console.WriteLine($"Auto-Scale: {autoScaling}");
Console.WriteLine($"Max Retries: {maxRetries}");
Console.WriteLine(new string('-', 35));
}
public static void Main() {
Console.WriteLine("=== C# Named & Optional Parameter Pipelines ===\n");
// 1. Invoking with only the required parameter (all defaults used)
Console.WriteLine("[Call 1: Default configuration]");
DeployCluster("cluster-alpha");
// 2. Invoking with positional overrides
Console.WriteLine("[Call 2: Positional overrides]");
DeployCluster("cluster-beta", 6, "eu-central-1");
// 3. Invoking with Named Arguments in arbitrary order
Console.WriteLine("[Call 3: Named arguments out of order]");
DeployCluster(
autoScaling: false,
clusterId: "cluster-gamma",
maxRetries: 2,
region: "ap-southeast-1"
);
}
}Expected Output:
=== C# Named & Optional Parameter Pipelines === [Call 1: Default configuration] Cluster: cluster-alpha Nodes: 3 Region: us-east-1 Auto-Scale: True Max Retries: 5 ----------------------------------- [Call 2: Positional overrides] Cluster: cluster-beta Nodes: 6 Region: eu-central-1 Auto-Scale: True Max Retries: 5 ----------------------------------- [Call 3: Named arguments out of order] Cluster: cluster-gamma Nodes: 3 Region: ap-southeast-1 Auto-Scale: False Max Retries: 2 -----------------------------------
How It Works: Step-by-Step
- Lines 5-11: Defines DeployCluster with required clusterId and 4 optional parameters with default values.
- Line 25: Invokes method supplying only required clusterId; nodeCount, region, autoScaling, maxRetries default automatically.
- Lines 33-38: Invokes method using named arguments (param: value) in completely reordered sequence.
Key Concepts
- Optional parameters must be declared at the end of the parameter list after all required parameters.
- Default values must be compile-time constants (literals, const expressions, or default(T)).
- Named arguments eliminate confusing boolean flags like DeployCluster("alpha", 3, true, false, 5) by explicitly specifying autoScaling: false.
- When compiling, the C# compiler bakes the default values directly into the call site in IL bytecode.
Common Mistake: Placing optional parameters before required parameters
All required parameters must precede optional parameters in the method signature. Having a required parameter after an optional one is a compile-time error.
❌ Incorrect
public void Setup(int port = 8080, string host) { } // Compile Error: Optional parameter cannot precede required parameter✅ Correct
public void Setup(string host, int port = 8080) { } // Correct: required parameter firstRelated C# Tutorials & Compiler
C# Lambda Expressions and Delegates (Action, Func)
Write functional C# code using Func, Action, and lambda expressions (x => x * 2).
C# Classes, Records, and Properties (get; set;)
Design objects using classes, auto-properties ({ get; set; }), and modern C# records.
C# Exception Handling: try, catch, finally, and Exception Filters
Catch and handle exceptions with try, catch, finally, and C# exception filters (when).
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.