I’m feeling quite confused about the way either C#‘s foreach and Java‘s enhanced for works and even more frustrating is to realize why I haven’t came across this detail before.
But anyway the fact of the matter is, I’d really like to understand why this apparently similar flow control statements work so differently. For illustration purposes let’s assume we need to iterate through an array of integers, with both implementations being something like:
C# 4.0 (code)
class Program
{
public static void Main(string[] args)
{
int[] foobar = new int[] {0, 1, 1, 2, 3, 5, 8, 13, 21};
Console.WriteLine(String.Format("[DEBUG] type: {0}", foobar.GetType()));
Console.WriteLine(String.Format("[DEBUG] length: {0}", foobar.Length));
try
{
for (int i = 0; i < foobar.Length; i++)
{
Console.Write(String.Format("{0} ", foobar[i]));
}
Console.Write(Environment.NewLine);
foreach (var i in foobar) {
Console.Write(String.Format("{0} ", foobar[i]));
}
}
catch (Exception exception)
{
Console.Write(Environment.NewLine);
Console.WriteLine(exception.ToString());
}
finally
{
Console.Write(Environment.NewLine);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
C# 4.0 (output)
[DEBUG] type: System.Int32[]
[DEBUG] length: 9
0 1 1 2 3 5 8 13 21
0 1 1 1 2 5 21
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Dotnet.Samples.Sandbox.Program.Main(String[] args) in e:\My Dropbox\Work\P
rojects\scm\git\sandbox\Dotnet.Samples.Sandbox\Dotnet.Samples.Sandbox\Program.cs
:line 51
Press any key to continue . . .
JAVA SE6 (code)
class Program {
public static void main(String[] args) {
int[] foobar = new int[] {0, 1, 1, 2, 3, 5, 8, 13, 21};
System.out.println("[DEBUG] type: " + (foobar.getClass().isArray() ? "Array " : "") + foobar.getClass().getComponentType());
System.out.println("[DEBUG] length: " + foobar.length);
try {
for (int i = 0; i < foobar.length; i++)
{
System.out.print(String.format("%d ", foobar[i]));
}
System.out.print(System.getProperty("line.separator"));
for (int i : foobar) {
System.out.print(String.format("%d ", foobar[i]));
}
} catch (Exception e) {
System.out.print(System.getProperty("line.separator"));
System.out.println(e.toString());
}
}
}
JAVA SE6 (output)
[DEBUG] type: Array int
[DEBUG] length: 9
0 1 1 2 3 5 8 13 21
0 1 1 1 2 5 21
java.lang.ArrayIndexOutOfBoundsException: 13
In the C# version..
..should be..
Doing a
foreachover an array of integers, as you are, does not iterate over array indices: it iterates over the integers.Given the array..
..your code was: