views:

143

answers:

6
+7  Q: 

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 };
+6  A: 

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.

Eric J.
+3  A: 

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

SQueek
A: 

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.

kahoon
+3  A: 

In this particular case, the type of productInfos is a compiler-generated Anonymous Type with 3 properties, ProductName, Category and Price.

Mark Simpson
+8  A: 

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 refer to it.
  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.
Cole
That's a good answer, but not 100% correct. It's quite possible to refer to the CompilerGeneratedType. Not directly by name, but certainly indirectly. For example: var test = new { P1="Hello", P2="Bye" }; Type t = test.GetType(); yields a concrete type with a concrete name, in my concrete example case UnderlyingSystemType: {<>f__AnonymousType0`2[System.String,System.String]}.
Eric J.
+2  A: 

var = programmer friendly = less typing = makes you lazy(another way of looking at it) = brings obscurity to code if new to 3.5 FW

System.ArgumentException