Var versus IEnumerable
The var keyword is new to C# 3.0 and enables you to implicitly declare variables at the method scope.
The great thing about it is that the implicitly typed variable is just as strongly typed as its explicitly
declared counterpart. For example, these variables
var blah = "S"
var moreblah = 50
are equivalent to the following:
string blah = "S"
int moreblah = 50
In the early days, the word ‘‘var’’ stood for variant. Today, that isn’t the case; in C# and VB.NET, var is a
specific keyword that, when used, tells the compiler to determine the exact type of the variable.
The IEnumerable<T> interface, new in .NET Framework 2.0, supports a simple iteration over a
collection of a specified type. It exposes the IEnumerator<T> interface, which is the base interface for
all generic enumerators. LINQ takes advantage of this enumeration via the foreach statement, which
lets you iterate through an enumeration without the complexity of dealing with and manipulating the
enumerator directly.
IEnumerable is minimal in its functionality, however. It has forward-only movement in a collection, so
moving back and forth among data items is not possible with IEnumerable.
With LINQ, it is important is to know when to use var versus IEnumerable. As you saw earlier in this
section, var can be used to implicitly declare a variable.While this is optional, it can be overused. The best
time to use var is when a variable is initialized with an anonymous type, only because in that scenario
it’s required. Using var too many times can also make your source code less readable by developers who
come in after you. In other words, don’t overuse var.
To understand the difference between the two and when one should be used over the other, consider the
following two examples. The first query uses var, but it is not necessary because the query result type
can be explicitly stated as an IEnumerable<int>, meaning that the result types are known.
int[] nums = {5, 1, 9, 4, 8, 11, 6, 14, 2, 7};
var query =
from num in nums
where num % 2 == 1
select num;
The next example, however, must use var because the result types are not known. The result
is a collection of anonymous types. In these cases, the name of the type is not available until the
compiler creates it.
Var query =
from prod in Products
where prod.ProductID = 10021
select new {prod.ProductName, prod.Price};