Hi
Another of the new feature of C# 3.0 is the implicitly typed local variable. For this a new keyword var is introduced in the C# list of keyword. The keyword allows the developer to declare variables without specifying its type. Hence the following lines will compile in C Sharp 3.0(This will not compile in C Sharp 2.0 or below).
var x = 5;
var y = "hello";
Console.WriteLine(x.GetType());
Console.WriteLine(y.GetType());
The result will be System.Int32 and s System.String. This does not mean that C # is no longer a strongly typed languages. Also C# 3.0 support implicit types and not variant types and hence the following will not be compiled.
var x = 5;
x = "hello";
As I said before C# is still a strongly typed language and once the implicit type has been inferred during compilation it cannot ne changed.
An interesting feature of the var keyword is its ability to free us from having to change calls to a method that return a certain type of object. In C# 2.0, if we needed to call a method that returned a Employee object, we would write something like this.
Employee myEmployee = GetByName("SomeID");
If at some point the GetByName method returns something other than a Employee object, this code will not compile.
But, if we use the var keyword we will be freed of worrying about the type returned by the GetByName method.
var SomeData = GetByName("someID");
Now the GetByName method could be changed to return a user object and the method call would still be valid, due to the fact that the var keyword is being utilized.
The bigger use of the var keyword is in the LINQ query, but that’s another post.
Thanks
Vikram