marți, 10 noiembrie 2009

[C#] "var"

-> The compiler infers the type indicated by "var" from the expression used to initialize the variable, and the IL code contains the inferred type.

var i = 10;
Console.WriteLine(i.GetType()) ; // write on console "SystemInt32"
The following code is not compiling:
var i = 10;
i = "George";
Use "var" to:
- Refer anonymous types
var _anonymous = new { Name = "George" };

- Refer query expressions
var _queryExpr = from devs in developers
where devs.Name = "George"
select new { devs.Name, devs.Age }

- Refer complex generic types
var _stringList = new List();

Not recommended to use "var":
- with known types (var dev = new Developer())
- with constants (var i = 5;)
you can't do anything with the variable without casting it back to the original type.
- with simple expression assignments (var _count = _list.Count)
- with variables where types cannot be inferred or where inferred type is not what is intended (want to use IList, but initialize with "var")

Niciun comentariu:

Trimiteți un comentariu