C# 3.0 – New features – Part 1
January 20, 2007 § 2 Comments
If you listened to the two channel 9 videos I posted you might have heard a lot about functional programming, Lambda expressions, LINQ and so on. It was overwhelming to hear so many terms all at once and not know what exactly each meant. On top of that the speakers talked about multi-core and concurrency and my head started spinning, so I decided I would learn each of the terms mentioned and even better record it for others and myself for future reference.
Instead of going into the details of different terms used above let’s see first hand what exactly we will be able to do in C# 3.0.
var customers = BusinessLogic.GetCustomers();
The above statement gives a sense of dynamism to C#. You would be thinking that you no longer have to specify the Type hence C# has become like VB where customer can be of any Type. While the first conclusion is correct, the second one is not. With the above statement the compiler tries to infer the Type using the right side of the expression. If it cannot figure it out, it throws an error. Also, after the above statement, if you write the following statement the compiler will throw an error:
customers = 10;
Although this syntactic sugar makes C# appear like a dynamic language, in reality it is actually statically Typed. Also note that you can only use the var keyword with local variables. There are a few other restrictions and you can read some of them here. There have been many times when I have felt a bit retarded to type the Type of a class two times. For Example Customer c = new Customer(); instead var c = new Customer(); makes it much simpler.
The real reason var was added is so that we can declare a strongly typed variable without needing to know the name of the variable’s type. This is required in order to enable another new C# 3.0 language feature: anonymous types. You wouldn’t be able to declare a variable of an anonymous type if you always had to include the type name as part of the variable declaration. That’s the main reason var has been added to the language.
– from this article by Ian Griffiths
More to come …