How to: Use Implicitly Typed Local Variables and Arrays in a Query Expression (C# Programming Guide)


You can use implicitly typed local variables whenever you want the compiler to determine the type of a local variable. You must use implicitly typed local variables to store anonymous types, which are often used in query expressions. The following examples illustrate both optional and required uses of implicitly typed local variables in queries.

Implicitly typed local variables are declared by using the var contextual keyword. For more information, see Implicitly Typed Local Variables (C# Programming Guide) and Implicitly Typed Arrays (C# Programming Guide).


The following example shows a common scenario in which the var keyword is required: a query expression that produces a sequence of anonymous types. In this scenario, both the query variable and the iteration variable in the foreach statement must be implicitly typed by using var because you do not have access to a type name for the anonymous type. For more information about anonymous types, see Anonymous Types (C# Programming Guide).

private static void QueryNames(char firstLetter)
    // Create the query. Use of var is required because
    // the query produces a sequence of anonymous types:
    // System.Collections.Generic.IEnumerable<????>.
    var studentQuery =
        from student in students
        where student.FirstName[0] == firstLetter
        select new { student.FirstName, student.LastName };

    // Execute the query and display the results.
    foreach (var anonType in studentQuery)
        Console.WriteLine("First = {0}, Last = {1}", anonType.FirstName, anonType.LastName);


The following example uses the var keyword in a situation that is similar, but in which the use of var is optional. Because student.LastName is a string, execution of the query returns a sequence of strings. Therefore, the type of queryID could be declared as System.Collections.Generic.IEnumerable<string> instead of var. Keyword var is used for convenience. In the example, the iteration variable in the foreach statement is explicitly typed as a string, but it could instead be declared by using var. Because the type of the iteration variable is not an anonymous type, the use of var is an option, not a requirement. Remember, var itself is not a type, but an instruction to the compiler to infer and assign the type.

// Variable queryID could be declared by using 
// System.Collections.Generic.IEnumerable<string>
// instead of var.
var queryID =
    from student in students
    where student.ID > 111
    select student.LastName;

// Variable str could be declared by using var instead of string.     
foreach (string str in queryID)
    Console.WriteLine("Last name: {0}", str);