Information Technology Reference
In-Depth Information
The Iteration Variable Is Read-Only
Since the value of the iteration variable is read-only, clearly, it cannot be changed. But this has
different effects on value type arrays and reference type arrays.
For value type arrays, this means that you cannot change the data of the array. For exam-
ple, in the following code, the attempt to change the data in the iteration variable produces a
compile-time error message:
int[] arr1 = {10, 11, 12, 13};
foreach( int item in arr1 )
item++; // Wrong. Changing variable value is not allowed
For reference type arrays, you still cannot change the iteration variable, but the iteration
variable only holds the reference to the data, not the data itself. You can , therefore, change the
data through the iteration variable.
The following code creates an array of four MyClass objects and initializes them. In the first
foreach statement, the data in each of the objects is changed. In the second foreach statement,
the changed data is read from the objects.
class MyClass
{
public int MyField = 0;
}
class Program {
static void Main() {
MyClass[] mcArray = new MyClass[4]; // Create array
for (int i = 0; i < 4; i++)
{
mcArray[i] = new MyClass(); // Create class objects
mcArray[i].MyField = i; // Set field
}
foreach (MyClass item in mcArray)
item.MyField += 10; // Change the data.
foreach (MyClass item in mcArray)
Console.WriteLine("{0}", item.MyField); // Read the changed data.
}
}
This code produces the following output:
10
11
12
13
Search WWH ::




Custom Search