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

You must use implicitly-typed local variables to store anonymous types. You can also use them in any other situation in which you want the compiler to determine the type of a local variable (in other words a variable declared at method scope). The following examples show how to use implicitly typed variables in both scenarios.

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).

Example

The following example shows how to use the var keyword in a common scenario where it is required: when you are creating and executing a query expression that produces a sequence of anonymous types. Note that in this scenario, not only the query variable, but also the iteration variable in the foreach statement must be implicitly typed by using var.

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

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

The example later in this topic shows how to use the var keyword as a syntactic convenience even when it is not required. To illustrate this construction, only the query variable is implicitly typed. The iteration variable in the foreach statement is explicitly typed but it can also be declared by using var. Remember, var itself is not a type, but rather an instruction to the compiler to infer and assign the type.

var queryID =
    from student in students
    where student.ID > 111
    select student.LastName;

foreach (string str in queryID)
{
    Console.WriteLine(str);
}

See Also

Concepts

C# Programming Guide

LINQ Query Expressions (C# Programming Guide)

Reference

Extension Methods (C# Programming Guide)

var (C# Reference)

Other Resources

Language-Integrated Query (LINQ)