From Visual C #3.0, variables declared in the method range can have implicit type var. Implicit local variables are strongly typed (as if you have declared this type), but the type is determined by the compiler. The following two I declarations are functionally equivalent:
var i = 10; // implicitly typedint i = 10; //explicitly typed
The following example demonstrates two Query expressions. In the first expression, var is allowed but not required, because the type of the query result can be explicitly declared as IEnumerable <string>. However,Var must be used in the second expression, because the result is an anonymous type set, and the name of this type can only be accessed by the compiler.. Note that in the second example, the foreach iteration variable item must also be converted to an implicit type.
// Example #1: var is optional because// the select clause specifies a stringstring[] words = { "apple", "strawberry", "grape", "peach", "banana" };var wordQuery = from word in words where word[0] == 'g' select word;// Because each element in the sequence is a string, // not an anonymous type, var is optional here also.foreach (string s in wordQuery){ Console.WriteLine(s);}// Example #2: var is required because// the select clause specifies an anonymous typevar custQuery = from cust in customers where cust.City == "Phoenix" select new { cust.Name, cust.Phone };// var must be used because each item // in the sequence is an anonymous typeforeach (var item in custQuery){ Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);}