var i = 5; var s = "Hello"; var d = 1.0; var numbers = new int[] {1, 2, 3}; var orders = new Dictionary();The implicitly typed local variable declarations above are precisely equivalent to the following explicitly typed declarations:
int i = 5; string s = "Hello"; double d = 1.0; int[] numbers = new int[] {1, 2, 3}; Dictionary orders = new Dictionary();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 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:
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