Thursday, June 01, 2006

C# 3.0 Specifications for May 2006

If you have visited the Future Versions page of the Microsoft Visual C# Development Center, you may have already browsed through the C# 3.0 documentation that is already available. Since I have been studying the May 2006 version of the C# 3.0 Specification, I’ll quickly provide a summary of the most important aspects.

  • Implicitly typed local variables and arrays. With the use of the var keyword, the compiler will try to determine (infer) the appropriate type of the variable without the need to expliclty specify the type of variable. This works both for simple variables and arrays. Although that sounds really convenient, I’m afraid this feature will be error prone. I already see a coding standard rule appearing…
  • Extension methods. This allows you to add new members to existing classes even if you do not have the source code. For instance, you can add a new member to the built-in String class without deriving from it or modifying its existing code. Quite a cool and handy feature.
  • Lambda expressions. Introduces a new syntax for defining a delegate handler with less code than anonymous methods already require. It supports defining both statements and expressions in one line (e.g. x => x+1).
  • Object initializers. In a similar fashion as arrays can be initialized, we can now initialize any object during its construction. C# 3.0 introduces a new syntax that allows calling the default constructor while initializing one or more of its properties in one statement.
  • Collection initializers. It was already possible to initialize an array with a collection of values, but now we can also initialize collections as well as long as they implement ICollection.
  • Anonymous types. With the combined efforts of the var keyword and the object initialization features, you can now create an instance of an anonymous class that is defined when you create it. Nevertheless, since you cannot refer to that instance other than through the variable, I’m not sure how it is useful other than in the LINQ stuff (see below).

Although most of those new features can be quite useful on its own, looking more closely at the syntax and examples of the new Query expressions (LINQ) reveals that they have been introduced for facilitating the query expressions. This new syntax allows a developer to use a kind of SQL statement right into your code. The compiler will translate this syntax into a hierarchy of method calls on a type that supports the Query Expression Pattern, a set of methods and properties required for supporting query expressions. This potentially allows a developer to perform queries on multiple data sources such as databases, XML documents, or other relational data structures. Check out this article to get a feeling on what you can do with it. (It’s from September 2005 though, so some stuff may have changed already).