views:

56

answers:

6
IEnumerable<Department> myQuery = (from D in myContext.Departments orderby D.DeptName select D);

var myQuery = (from D in myContext.Departments orderby D.DeptName select D);

What is the difference between these two statements above? In my little asp.net/C#/ EF4.0 app I can write them either way, and as far as how I want to use them, they both work, but there has to be a reason why I would choose one over the other?

+2  A: 

The second one is shorter (assuming type of D is Department).

(actually, the return type of the query may be something other than IEnumerable, like IQueryable but the point is, the type will be statically inferred from the right hand side of the assignment operator instead of being explicitly mentioned in code).

Mehrdad Afshari
+2  A: 

syntactic convenience

rdkleine
+1  A: 

I believe in the 2nd case the type of myQuery is an IQueryable<Department> rather than IEnumerable. If you don't need anything specific to an IQueryable that you can't do with an IEnumerable then they behave the same.

The var keyword is just for convenience when the compiler can figure out the type without spelling it out. So instead of

MyReallyLongGenericClassName<SomeOtherType> myObject = new MyReallyLongGenericClassName<SomeOtherType>();

You can just write var myObject = new MyReallyLongGenericClassName<SomeOtherType>();

Davy8
+1  A: 

With var the compiler infers the type of myQuery. It would probably endup being an IQueryable<Department> rather than an IEnumerable<Department>.

Ben Robinson
+2  A: 
(from D in myContext.Departments orderby D.DeptName select D);

returns an object of type IQueriable<Department> which in turn implements IEnumerable<Department>

while you use the var keyword in here the compiler replace it with IQueriable<Department>

Itay
+1  A: 

The only difference here is that you're not declaring yourself the type of myQuery. You're taking advantage of a feature named Type Inference. Indeed the type returned will be IQueryable<Department> where the first statment explicitly types the variable as IEnumerable.

p.campbell