Use of var Within foreach Constructs
It is also possible to make use of implicit typing within a foreach looping construct. As you would
expect, the compiler will correctly infer the correct “type of type.” Consider the following method,
which iterates over an implicitly typed local array of integers:
static void VarInForeachLoop()
{
var evenNumbers = new int[] { 2, 4, 6, 8 };
// Use "var" in a standard foreach loop.
foreach (var item in evenNumbers)
{
Console.WriteLine("Item value: {0}", item);
}
}
Understand, however, that a foreach loop can make use of a strongly typed iterator when pro-
cessing an implicitly defined local array. Thus, the following code is also syntactically correct:
static void VarInForeachLoop()
{
var evenNumbers = new int[] { 2, 4, 6, 8 };
Do'stlaringiz bilan baham: |