Default Parameters and Named Parameters in C#
Introduction
In C#, methods can have default parameters, which allow you to specify default values for parameters. You can also use named parameters, which allow you to specify arguments by parameter name, making your method calls clearer and more readable.
Default Parameters
Default parameters allow you to provide a default value for a method parameter, so if no argument is passed, the default value is used.
Example: Using Default Parameters
void Greet(string name = "Guest")
{
Console.WriteLine("Hello, " + name);
}
Greet(); // Output: Hello, Guest
Greet("John"); // Output: Hello, John
In this example, the Greet
method has a default parameter name
with a default value of "Guest". If no argument is passed, it prints "Hello, Guest".
Named Parameters
Named parameters allow you to specify arguments by the parameter name instead of their position in the method call. This improves readability and makes the method calls more descriptive.
Example: Using Named Parameters
void OrderPizza(string size, bool cheese, bool pepperoni)
{
Console.WriteLine($"Ordered a {size} pizza with cheese: {cheese}, pepperoni: {pepperoni}");
}
OrderPizza(size: "Large", pepperoni: true, cheese: false);
// Output: Ordered a Large pizza with cheese: False, pepperoni: True
In this example, OrderPizza
is called with named parameters. The arguments are passed by specifying the parameter names, allowing for a more readable method call.
Combining Default and Named Parameters
You can combine default and named parameters in a method call to make the code more flexible and readable.
Example: Using Default and Named Parameters
void BookTicket(string destination = "New York", string seatType = "Economy", bool meals = true)
{
Console.WriteLine($"Booking to {destination}, Seat: {seatType}, Meals: {meals}");
}
BookTicket(meals: false); // Output: Booking to New York, Seat: Economy, Meals: False
In this example, the method BookTicket
uses both default and named parameters. By specifying only the meals
argument, the default values for destination
and seatType
are used.
Key Points to Remember
- Default parameters allow you to specify default values for method parameters, so you don't have to provide values every time you call the method.
- Named parameters let you specify arguments by name, making method calls clearer and more readable.
- You can combine default and named parameters for more flexible and readable code.