With Linq, the range variable (e) can be implicitly typed from the array/collection (emps) it is coming from, but a foreach statement cannot do the same thing without the var keyword, or a type. Why is this?
In ex1 the compiler knows e is of type Employee, without giving a var keyword or anything. Why can’t the foreach loop in ex2 do the same thing, you have to provide the type (whether its var or some type).
ex1.
Employee[] emps = {new Employee ( 1, "Daniel", "Cooley", 7, 57.98M };
public void SortByLastname()
{
var sortedByLastname =
from e in emps
orderby e.LastName
select e.FirstName;
}
ex2.
foreach (Employee empl in emps)
{
Console.WriteLine("Employee " + empl);
}
This may be over analyzing but i’m trying to get to the bottom of why this is the case.
The answer may very well be Linq query syntax is set up to auto deduce the type of the range variable and the foreach statment is not. Can someone help explain why this is?
The reason you do not need to list the type is because this is being broken down (basically) extension methods. You should be able to rewrite ex2 as:
Notice that you do not need to explicitly say the type as it is inferred from
empsSo ex1 will break down to:
For a much fuller understanding of this and more, I really suggest buying Jon Skeets book C# In Depth Second Edition