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;)
->
- 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