Thursday, November 06, 2008

C# 4.0 : Optional Parameters

C# 4.0 Feature list looks promising and adds more flexiblity to the programmer.

Of course, i dont have hands on experience with this features as it is yet be released for beta, my knowledge is purely based on the blog entries by Bart De Smet in his blogs.

First feature i would like to focus is a long-standing request for any C# programmer,The Optional Parameters for methods.

Optional parameters also bring along default values for parameters.

The syntax is very much simple and straightforward.

public static void SayHello(string s = "hello")
{
// body
}


The developer can invoke the SayHello method with or without an arguement, which case the default value would be used.

SayHello();
SayHello("welcome c# 4.0");


One important point to note here is, all optional parameters needs to come at the end of the arguement list.The reason for this is obvious, to remove chances of ambiguities which may be resulted

public static void SayHello(string s1 = "Hello World!", string s2)


What would a call with a single string argument result in? Would the parameter be bound to s1, overriding the default, or would it bind to s2?