C# for Java Programmers

The foreach Statement

The foreach statement is a language construct that is very useful and is currently not available in the Java language; in fact its origins can be traced back to Visual Basic. It is an iteration statement, but was not mentioned earlier as it is used on arrays and other container classes. Container classes include Arrays, preexisting container classes in the System.Collection namespace, as well as collections created by you that support the IEnumerable interface. We will provide more detail on the container classes later in this chapter.

In the last two sections I mentioned how use of the foreach statement would have been superior to for loops. If you recall, a for loop has several elements a counter, a control condition, and an increment operation on the counter. In the for loop you need to keep in mind the number of elements in the array you are iterating through, or you will end up throwing an index out of range exception. It is very easy to miscalculate the number of iterations a for loop will go through before meeting its control condition. Even experienced programmers make that mistake every now and then, myself included. The foreach statement takes away many of the opportunities where we might shoot ourselves in the foot, yet leaves us with the functionality we wanted.

The following code snippet demonstrates iteration through an integer array using the for loop.

int[] IntArray = new...

UNLIMITED FREE ACCESS TO THE WORLD'S BEST IDEAS

SUBMIT
Already a GlobalSpec user? Log in.

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.

Customize Your GlobalSpec Experience

Category: Field-Programmable Gate Arrays (FPGA)
Finish!
Privacy Policy

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.