What does var
really do in the following case?
var productInfos =
from p in products
select new { p.ProductName, p.Category, Price = p.UnitPrice };
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 use the type name in the declaration.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With