This blog post summarizes the new features of C# langauge shipped with Orcas (VS 2005).
Below are the new features been introduced.
§ Automatic Properties
§ Object Initializers
§ Collection Initializers
§ Extension Methods
§ Lambda Expressions - p => expressions
§ Query Syntax
§ Anonymous Types
· Concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.
· Particularly useful when querying and transforming/projecting/shaping data with LINQ.
§ Var Keyword
"Orcas" introduces a new var keyword that may be used in place of the type name when performing local variable declarations.
For example, I could use the var keyword like below to declare three variables:
var name = "Arun";
var age = 30;
var male = true;
The compiler will infer the type of the "name", "age" and "male" variables based on the type of their initial assignment value (in this case a string, an integer, and a boolean). This means it will generate IL that is absolutely identical to the code below:
string name = "Arun";
int age = 30;
bool male = true;
The CLR actually never knows that the var keyword is being used - from its perspective there is absolutely no difference between the above two code examples. The first version is simply Syntactic Sugar provided by the compiler that saves the developer some keystrokes, and has the compiler do the work of inferring and declaring the type name.
The var keyword can be used to reference any type in C# - meaning it can be used with all three Explictly Declared Types [As above], Custom Types and Anonymous Types.
Explictly Declared Types: As Above.
In addition to using built-in datatypes with the var keyword, you can obviously also use any Custom Types you define. For example, I could go back to the LINQ query projection, that uses an explicit "MyProduct" type for the data-shaping and adapt it to use the var keyword like so:
Same as ‘Custom Types’ except when instantiating anonymous types you instead just leave the type-name blank after the "new" keyword:
Hope this helps.
Thanks & Regards,
Arun Manglick || Tech Lead