Optional parameters in C# allow you to define method parameters with default values. This feature enhances method flexibility and simplifies method calls by allowing arguments to be omitted when invoking the method.
To create an optional parameter, assign a default value in the method declaration. Here's a simple example:
public void Greet(string name = "Guest")
{
Console.WriteLine($"Hello, {name}!");
}
In this example, "Guest" is the default value for the name
parameter.
When calling a method with optional parameters, you can either provide a value or omit it:
Greet(); // Outputs: Hello, Guest!
Greet("Alice"); // Outputs: Hello, Alice!
C# allows multiple optional parameters in a method. However, they must be placed at the end of the parameter list:
public void DisplayInfo(string name, int age = 30, string city = "Unknown")
{
Console.WriteLine($"{name}, Age: {age}, City: {city}");
}
DisplayInfo("Bob"); // Outputs: Bob, Age: 30, City: Unknown
DisplayInfo("Alice", 25); // Outputs: Alice, Age: 25, City: Unknown
DisplayInfo("Charlie", 35, "New York"); // Outputs: Charlie, Age: 35, City: New York
While Method Overloading can achieve similar results, optional parameters often lead to cleaner and more maintainable code. Consider this comparison:
// Using optional parameters
public void Process(int id, string name = "Default", bool isActive = true)
{
// Implementation
}
// Equivalent using method overloading
public void Process(int id)
{
Process(id, "Default", true);
}
public void Process(int id, string name)
{
Process(id, name, true);
}
public void Process(int id, string name, bool isActive)
{
// Implementation
}
The optional parameter approach reduces code duplication and simplifies method signatures.
Optional parameters in C# provide a powerful way to create more flexible and convenient method signatures. They simplify method calls, reduce the need for overloading, and can lead to more readable and maintainable code. When used judiciously, optional parameters can significantly enhance the usability of your C# methods and classes.