Implicitly Typed Local Variables
Now, let's go back to the declaration of query results where you declare the result as type var:
var result = ...
Because the select clause returns an instance of an anonymous type, you cannot define an explicit type IEnumerable<T>. Fortunately, C# 3.0 provides another feature—implicitly typed local variables—that solves this problem.
You can declare an implicitly typed local variable by specifying its type as var:
var id = 1;
var name = "Keith";
var customers = new List<Customer>( );
var person = new {FirstName = "Donna", LastName = "Gates", Phone="123-456-7890" };The C# compiler infers the type of an implicitly typed local variable from its initialized value. Therefore, you must initialize such a variable when you declare it. In the preceding code snippet, the type of id will be set as an integer, the type of name as a string, and the type of customers as a strongly typed List<T> of Customer objects. The type of the last variable, person, is an anonymous type containing three properties: FirstName, LastName, and Phone. Although this type has no name in our code, the C# compiler secretly assigns it one and keeps track of its instances. In fact, the Visual Studio IDE IntelliSense is also aware of anonymous types, as shown in Figure 13-1.

Figure 13-1. Visual Studio IntelliSense recognizes anonymous types
Back in Example 13-3, result is an instance of the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access