C# 3.0 Features. Part III: The var keyword
Previous materials of C# 3.0 Feature series:
“var” keyword
During the local variable declaration we have to explicitly specify the type even if the variable doesn’t have any value yet. The “var” expression brings as ability do not specify the type during local variable declaration. The compiler will get it from the initializer.
Let’s declare two local variables of the same type (User) but one will be declared in standard (old) way and another one with using “var” keyword.
1: User userTodd = new User() { UserName = "Todd" }; 2:
3: var userBob = new User() {UserName = "Bob"};
Disassembler shows that both variables (userTodd and userBob) have the same type CSharp30Features.User even we did not explicitly specify the type in case of userBob variable.

Also keep in mind that ones the variable has been initialized by one type it won’t be possible to reassign it to another type. We will get compile time error:
1: var someVar = 1;
2: someVar = "This assignment will bring compile time error";
Why to use “var” keyword?
The obvious question is what is the advantage of using “var” keyword.
Redundancy in expression
We do not need to specify type twice in local variable declaration expression.
1: SomeType varName = new SomeType();
The right side of the expression already shows which type variable will be. It is enough to specify it just ones:
1: var varName = new SomeType();
Anonymous Types support.
“var” expression became necessarily after introducing the Anonymous Types. In case of Anonymous Type declaration we cannot use standard expression as the type which variable has to be assign to is unknown.
1: ??? someVar = new {Property1="value", Property2="Another value"};
This is a valid expression for Anonymous Types:
1: var someVar = new {Property1="value", Property2="Another value"};
I am planning to speak explicitly about Anonymous Types in my next upcoming blog post “C# 3.0 Features. Part IV: Anonymous Types”
Technorati tags:
.Net,
C# 3.0,
Var