Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
for
foreach
loop

What is the foreach loop in C#?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The foreach loop in C# executes a block of code on each element in an array or in another collection of items; i​t is useful for performing the same function on each item.

svg viewer

Syntax

Have a look at the syntax of the foreach loop in C#:

foreach(data_type var_name in collection_variable)
{
     // statements to be executed
}
  • data_type can be any data type compatible with C#.
  • collection_variable can be any collection of elements (e.g., a list or an array).

The data_type must match the data type of the elements in the collection_variable.

Code

The code snippet below illustrates the usage of the C# foreach loop:

class ForEachDemo
{
static void Main()
{
// an array of fruit names
string[] Fruits = {"Apple", "Banana", "Apricot", "Kiwi", "Mango"};
// printing the elements of the Fruits array using foreach
foreach (string fruit in Fruits)
{
System.Console.WriteLine(fruit);
}
}
}

RELATED TAGS

c#
for
foreach
loop
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring