Author Topic: C# and var keyword (Implicitly Typed Local Variables)  (Read 14172 times)

Offline admin

  • Administrator
  • Sr. Member
  • *****
  • Posts: 296
    • View Profile
C# and var keyword (Implicitly Typed Local Variables)
« on: December 20, 2008, 09:31:49 PM »
Implicitly Typed Local Variables
In an implicitly typed local variable declaration, the type of the local variable being declared is inferred from the expression used to initialize the variable. When a local variable declaration specifies var as the type and no type named var is in scope, the declaration is an implicitly typed local variable declaration. For example:
Code: [Select]
var i = 5;
var s = "Hello";
var d = 1.0;
var numbers = new int[] {1, 2, 3};
var orders = new Dictionary<int,Order>();
The implicitly typed local variable declarations above are precisely equivalent to the following explicitly typed declarations:

Code: [Select]
int i = 5;
string s = "Hello";
double d = 1.0;
int[] numbers = new int[] {1, 2, 3};
Dictionary<int,Order> orders = new Dictionary<int,Order>();
A local variable declarator in an implicitly typed local variable declaration is subject to the following restrictions:

The declarator must include an initializer.
The initializer must be an expression. The initializer cannot be an object or collection initializer (§26.4) by itself, but it can be a new expression that includes an object or collection initializer.
The compile-time type of the initializer expression cannot be the null type.
If the local variable declaration includes multiple declarators, the initializers must all have the same compile-time type.
The following are examples of incorrect implicitly typed local variable declarations:

Code: [Select]
var x;               // Error, no initializer to infer type from
var y = {1, 2, 3};   // Error, collection initializer not permitted
var z = null;         // Error, null type not permitted
For reasons of backward compatibility, when a local variable declaration specifies var as the type and a type named var is in scope, the declaration refers to that type; however, a warning is generated to call attention to the ambiguity. Since a type named var violates the established convention of starting type names with an upper case letter, this situation is unlikely to occur.

The for-initializer of a for statement (§8.8.3) and the resource-acquisition of a using statement (§8.13) can be an implicitly typed local variable declaration. Likewise, the iteration variable of a foreach statement (§8.8.4) may be declared as an implicitly typed local variable, in which case the type of the iteration variable is inferred to be the element type of the collection being enumerated. In the example

Code: [Select]
int[] numbers = { 1, 3, 5, 7, 9 };
foreach (var n in numbers) Console.WriteLine(n);
the type of n is inferred to be int, the element type of numbers.