Sunday, November 2, 2008

C# 4.0

Now that PDC 2008 is over, you've probably heard all about C# 4.0. Seems like there are lots of possibilities to explore on the new dynamic keyword. The two top features I immediately like, are named parameters, and covariance.

Here is an example of a method taking three parameters, where the first is required, and the remaining two are optional:

public void Method(int a, int b = 7, int c = 10)
{

}

Note that optional parameters must be placed at the end of the parameter list.

Now, to call this method, you have several options, since you don't have to specify the parameters in order, if you prefix them by their name. So, here some examples of valid method calls:

Method(1);
Method(1, c:0);
Method(1, b:10, c:30);

So, for the nice class library developer, this should make life easier, since you don't have to overload your class constructors, or methods, into many mutations, because you want to accomodate all kinds of scenarios in your class.

Check out this Channel 9 video for a great demo of the new features from the C# team itself:
http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/

Also, Bart de Smets has a good blog entry on optional parameters:
http://community.bartdesmet.net/blogs/bart/archive/2008/10/31/c-4-0-feature-focus-part-1-optional-parameters.aspx

And finally, Anders Noraas has a good article on covariance:
http://andersnoras.com/blogs/anoras/archive/2008/10/28/c-4-0-covariance-and-contra-variance.aspx

No comments: