Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of var in linq

What does var really do in the following case?

var productInfos =
from p in products
select new { p.ProductName, p.Category, Price = p.UnitPrice };
like image 237
maztt Avatar asked May 02 '10 17:05

maztt


2 Answers

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:

  1. CompilerGeneratedType will be generated by the compiler so it's impossible for you to use the type name in the declaration.
  2. You don't have to think too hard about the collection type of the result. Linq can do its thing and you don't have to worry about it.
like image 87
mrmcgreg Avatar answered Dec 15 '22 00:12

mrmcgreg


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.

like image 40
Eric J. Avatar answered Dec 14 '22 23:12

Eric J.