What does var
really do in the following case?
var productInfos =
from p in products
select new { p.ProductName, p.Category, Price = p.UnitPrice };
What does var
really do in the following case?
var productInfos =
from p in products
select new { p.ProductName, p.Category, Price = p.UnitPrice };
Var is a placeholder for a compiler-created ("anonymous") type that has three properties, ProductName, Category and Price.
It is NOT a variant (e.g. as in Visual Basic). It is a concrete type and can be used as such in other places in the code.
variables with var are implicitly typed local variable which are strongly typed just as if you had declared the type yourself, but the compiler determines the type. it gets the type of the result.
and here a nice read C# Debate: When Should You Use var?
and here another C# 3.0 Tutorial
It eases you from the pain of having to declare the exact type of your query result manually. But I have to empathize, this is not dynamic typing: the productInfos
variable will have a static type, but it is created by the compiler instead of you.
In this particular case, the type of productInfos is a compiler-generated Anonymous Type with 3 properties, ProductName, Category and Price.
The two lines:
var productInfos = from p in products
select new { p.ProductName, p.Category, Price = p.UnitPrice };
and
IEnumerable<CompilerGeneratedType> productInfos = from p in products
select new { p.ProductName, p.Category, Price = p.UnitPrice };
are equivalent. CompilerGeneratedType
is a type that will be created by the compiler and has the three public properties ProductName, Price, and Category
. var
is helpful for two reasons:
CompilerGeneratedType
will be generated by the compiler so it's impossible for you to refer to it.var = programmer friendly = less typing = makes you lazy(another way of looking at it) = brings obscurity to code if new to 3.5 FW