1.8. Implicitly Typed Local Variables

A new keyword, var, has been added to C#. When the compiler sees it, it implicitly defines the type of the variable based on the type of expression that initializes the variable. While its use is mandatory with anonymous types, it can be applied even in other cases, such as the following:

  • var i = 5; is equivalent to int i = 5;

  • var s = "this is a string"; is equivalent to string s = "this is a string";

An implicitly typed local variable must have an initializer. For example, the following declaration is invalid:

var s; // wrong definition, no initializer

As you can imagine, implicit typing is really useful for complex query results because it eliminates the need to define a custom type for each result.

NOTE ...

Get LINQ for Visual C# 2008 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.