Feeds:
Posts
Comments

Posts Tagged ‘named parameter’

Howdy there,

Now it’s around a month, that Microsoft released the .NET framework 4 to the public – so I wanted to take the occasion to give you a quick view on two nice new features:

1. Optional parameters:

You can specify any parameters to be optional by assigning it a default value directly in the list of parameters (using the assignment operator). It is quite straight-forward:

 

   1: public static void DoSomething(Int32 count = 10)

   2: {

   3:     for (int i = 0; i < count; i++)

   4:     {

   5:         Console.WriteLine(i);

   6:     }

   7:     Console.ReadLine();

   8: }

Snippet 1: The DoSomething method, specifying the count parameter as optional

This changes also the way such a method can be called, i.e. by omitting the parameter it still works fine – it just assigns the default value (in our case 10), and the code can perfectly run like that. Hence, a call to the method may look like in the following example:

   1: static void Main(string[] args)

   2: {

   3:     DoSomething();

   4: }

Snippet 2: Call to DoSomething , omitting the parameter

Even IntelliSense takes notice of the optional parameters, displaying them in square brackets, along with its default value:

image

Figure 1: IntelliSense displaying an optional parameter

Straightforward so far, isn’t it?

2. Named parameters

Now, imagine a case where we have a method that defines two required parameters, followed by an optional parameter and then again followed by another requited parameter. Let’s change the DoSomething method so it looks like in snippet 3:

   1: public static void DoSomething(String name, String surname, String city = "Munich", Int32 age)

   2: {            

   3:     Console.WriteLine(name + " " + surname + " lives in: " + city + " / age:" + age;

   4: }

Snippet 3: The changed DoSomething  method

Now it is basically possible to change the order of the parameter calling by specfying the correct names followed by a colon and again followed by the value. That’s it!

 

   1: DoSomething(surname: "Miller", name: "John", age: 32);

   2: DoSomething(age:32, surname: "Miller", name: "John", city:"Berlin");

Snippet 4: Two ways of calling DoSomething, using named parameters

This feature is especially useful if you use optional parameters, since it may not become clear which parameter is called next if you omit an optional parameter. Again, IntelliSense gives useful hints when calling a named parameter.

Enjoy!

Best regards,

Martin

Read Full Post »