C# FAQ: What is the difference between CSharp and Java foreach loops

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

What is the difference between C# and Java foreach loops?

The foreach loop is a simple syntax for iterating through arrays or collections—implementing the Java: java.lang.Iterable interface or the C#: System.Collections.IEnumerable interface.

Whereas in the Java language, the for keyword and the : operator are used to create a foreach loop, the C# foreach and in keywords are used for this purpose.

// C# example
string[] oddBalls = {"one", "three", "five", "seven"};
 
foreach (string currentBall in oddBalls)
{
   Console.WriteLine (currentBall + " is an odd number.");
}
// Java example
String[] oddBalls = {"one", "three", "five", "seven"};
 
for (String currentBall : oddBalls)
{
   System.out.println (currentBall + " is an odd number.");
}

In C++, the syntax is for_each in <algorithm>.

See also


Personal tools