Thursday, January 7, 2010

Optional parameters in .NET 4.0

If you're wondering how you can use optional parameters in .NET 4.0 - here's a brief starter post:

When using optional parameters, you need to put your required parameters BEFORE the optional parameters. You define a parameter as optional by assigning a value to it directly within the method signature:


public static void GetCar(string maker, string color = "red", int year = 2009)
{
...
}


Here maker is a required parameter, but color is optional with a default value of red. If you don't specify anything else, it will default to red, and same for the year. Optional parameters always need a default option.

We can call it like this:


GetCar("Toyota"); // returns a red 2009 toyota
GetCar("Toyota", "blue") //returns a blue 2009 toyota
GetCar("Toyota", "blue", 2010) // returns a blue 2010 toyota

Aside from optional parameters, in .NET 4.0 you can specify the order of parameters to call in, or in the case of multiple optional parameters, specify values for certain ones by using ":". Let's say in our above method, we just want to pass in the color, but use the default year. We can call it like this:


GetCar(maker : "Toyota", color: "blue");


Very useful.