Δευτέρα, 29 Ιουνίου 2009 12:48 πμ
από το μέλος
Panagiotis Kefalidis
.NET 4 - C# 4.0 Optional and named parameters
One of the new cool features introduced in C# 4.0 is optional parameters. They’ve been around for a long time in other languages like C++ but also VB.NET (you can’t rub it in our faces anymore, can you?) and it was about time we get this feature implemented in C# too. Using optional parameters we can avoid a lot of overloading in our methods just to make sure we predicted all possible combinations and all default values in each overload.
So, how can I use it? It’s pretty straightforward. You just add an equal sign “=” next to your parameter and add the default value.
public void SaySomething(bool sayHello = false, bool sayGoodbye = false)
{
if (sayHello)
Console.WriteLine(“Hello!”);
if (sayGoodbye)
Console.WriteLine(“Goodbye!”);
}
Now what if I want to explicitly set the value for sayGoodbye to true and leave the rest as is? You can notice sayGoodbye is the SECOND parameter in my method so if I want to pass a value to it, I have to pass a value to sayHello too. This is were named parameters come to rescue. By calling the method as below, I explicitly set to true sayGoodbye but I leave sayHello to its default value.
SaySomething(sayGoodbye : true);
Named parameters syntax is <Parameter name> : <Value>