The "var" Keyword

 Some people may not be familiar with the use of the new "var" keyword.  The easiest way to explain it is: whatever your evaluation or return type of a method is, this is what the data type is.  If you do:

var values = CallSomeMethod(); //returns IEnumerable<int>

The values variable equates to IEnumerable<int>.  If you use a LINQ query:

var values = from c in Customers select c; //returns IQueryable<Customer>

The values variable is of the IQueryable<Customer> type, unless you use a LINQ to SQL method to transform the data as in the following:

var values = (from c in Customers select c).First(); //returns Customer
var values = (from c in Customers select c).ToList() //returns List<Customer>

In this case, the values are of a specific type returned from the method; in the case of LINQ queries, it infers the type as a collection based type (even if one result is returned; it can't know that at design time).  Because it can infer the type at design time, it knows what the type is and can give you intellisense.

However, if you assign it a null value, it will give you a design-time error.  This is because the compiler can't determine the underlying type.  At runtime, the value can be null, but not at design time.

Comments

No Comments