Pranay Rana: Implicitly typed local variables

Friday, October 22, 2010

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:
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

No comments:

Post a Comment