Variables | specification
Original: "C # Version 3.0 Specification", Microsoft
Translation: Lover_p
In a local variable declaration with an implicit type (implicitly typed local variable declaration), the type of the declared localized variable is inferred from an expression that initializes the variable. When a local variable sound is used to indicate character var instead of a type, and the current scope does not have a type named Var, the declaration becomes a local variable declaration with an implicit type. For example:
var i = 5;
var s = "Hello";
var d = 1.0;
var numbers = new int[] {1, 2, 3};
var orders = new Dictionary<int, order> ();
These implicitly-typed local variable declarations are exactly the same as those with explicit types:
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 declaration (declarator) in a local variable declaration with an implicit type must follow the following constraints:
L The declaration must contain an initializer.
The L-initializer must be an expression. The initializer cannot be its own object or collection initializer (part 4th), but it can be a new expression that contains an object or collection initializer.
L The type of an initializer expression must not be an empty type at compile time.
L If the declaration of a local variable contains more than one declaration, all initializers must have the same type at compile time.
The following is an incorrect example of an explicit, implicitly typed local variable sound:
var x; Error, no initializer to infer type
var y = {1, 2, 3}; Error, collection initializer not allowed
var z = null; Error, NULL type not allowed
For backward compatibility reasons, when a local variable declaration indicator is of type Var, but the current scope has a type named Var, the declaration uses that type; however, (the compiler) gives a warning for this ambiguous semantics. This should not happen, however, since Var violates the convention that the first letter of the type name must be capitalized.
The for-initializer of the For statement and the resource-acquisition of the using statement can be a local variable declaration with an implicit type. Similarly, an iteration variable in a foreach statement can be declared as a local variable with an implicit type, in which case the type of the iteration variable is inferred by the element type of the collection to be traversed.
int[] numbers = {1, 3, 5, 7, 9};
foreach (var n in numbers) Console.WriteLine (n);
In the example above, the type of n is inferred as the Int--numbers element type.