Friday, September 25, 2009

New features C# 3.0 :Implicitly Typed Local Variables

Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

The following examples show various ways in which local variables can be declared with var:
// i is compiled as an int
var i = 5;
// s is compiled as a string
var s = "Hello";
// a is compiled as int[]
var a = new[] { 0, 1, 2 };
// expr is compiled as IEnumerable
// or perhaps IQueryable
var expr = from c in customers
where c.City == "London"
select c;
// anon is compiled as an anonymous type
var anon = new { Name = "Terry", Age = 34 };
// list is compiled as List
var list = new List();

It is important to understand that the var keyword does not mean “variant” and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.
The var keyword may be used in the following contexts:
  • On local variables (variables declared at method scope) as shown in the previous example.
  • In a for initialization statement. for(var x = 1; x < 10; x++)
  • In a foreach initialization statement. foreach(var item in list){...}
  • In a using Statement using (var file = new StreamReader("C:\\myfile.txt")) {...}
 The following restrictions apply to implicitly-typed variable declarations:
  • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
  • var cannot be used on fields at class scope.
  • Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
  • If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

No comments: