Implicitly Typed Local Variables

Earlier we saw a new feature “Automatic Properties” in C# 3.0. Today we are going to see the use of new ‘var’ keyword.

C# 3.0 allows local variables in methods to have an implicit type by identifying it from the type of its initial value. For instance,

var str = “Adil“; // str is compiled as a string

var col = new[] { 0, 1, 2 }; // col is compiled as int[]

var anoType= new { Name = “Terry“, Age = 34 }; //anonymous type

When you call the GetType method on str, it will return System.String type.

A point of consideration is that var keyword is not like var in javascript and it does not mean that variable is late-bound. It is actually a keyword for compiler to determine and assign the type with respect to the value initialized.

Also note that var keyword cannot be used in class variables and also in passing variables to method or returning from method. It does not support nullable type as well. Further you need to give it some value at the time of declaring otherwise it will be an error. Let say,

var someVar;  someVar= 1; // not allowed

The var keyword does not impress until it is used with LINQ. We will see it’s use with LINQ in some later post.