Skip to content

Latest commit

 

History

History
30 lines (21 loc) · 2.85 KB

how-to-use-implicitly-typed-local-variables-and-arrays-in-a-query-expression.md

File metadata and controls

30 lines (21 loc) · 2.85 KB
title description ms.date helpviewer_keywords ms.topic ms.assetid
How to use implicitly typed local variables and arrays in a query expression
Use implicitly typed local variables in C# to have the compiler determine the type of a local variable. You must use them to store anonymous types.
07/20/2015
implicitly-typed local variables [C#], how to use
how-to
6b7354d2-af79-427a-b6a8-f74eb8fd0b91

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 and Implicitly Typed Arrays.

Examples

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.

[!code-csharpcsProgGuideLINQ#32]

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.

[!code-csharpcsProgGuideLINQ#33]

See also