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

Implicitly typed local variables cannot be used as method parameters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.139.172