Wednesday, 12 September 2007

C# 3.0 Basic - Implicit typing

var i = 5;
var s = "Hello";
var d = 1.0;
var numbers = new int[] {1, 2, 3};
var persons= new Dictionary<int,Order>();

Basically the above are equivalent to
int i = 5;
string s = "Hello";
double d = 1.0;
int[] numbers = new int[] {1, 2, 3};
Dictionary<int,Order> persons= new Dictionary<int,Order>();

"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". IntelliSense recognises the type of the variable and support normal auto completion of that type for the variable.

Note that the following are example of incorrect 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

1 comment: