Loading...

C# foreach

string[] plants = { "leaf", "mint" }; stores two words. Then foreach (string plant in plants) hands each word to the name plant, and Console.WriteLine(plant) writes it. The screen shows two lines: leaf, then mint. You do not write an index counter on this page. Keep the public class named Pine.

One name for each value in the array

Open the Pine file. The class name stays Pine. This page does not rename the type. Delete any for with break or continue if that shape is still there. Delete a counted for (int i = 1; i <= 5; i = i + 1) if it is still there. Delete any ReadLine line. The file you keep has no wait for typing, no early break, and no index counter. The screen is written only by the writing line inside the foreach braces.

Inside Main, store the array first: string[] plants = { "leaf", "mint" };. That line does not write the screen. It only keeps two words under the name plants. Then the loop:
foreach (string plant in plants) {
Console.WriteLine(plant);
}
The word foreach is lowercase, written as one word. Inside the parentheses sit the element type string, the name plant for one element, the word in, then the array name plants. That in is not a path and not a case label. It marks “each value from plants goes into plant.” The braces hold the body. Console.WriteLine(plant); writes the current word with no quotes around plant. Save the file.

The file you keep

Keep this teaching shape. One string[] named plants holding leaf then mint. One foreach with string plant in plants. One writing line that writes the bare name plant. There is no index i, no break, and no quotes around plant.

string array walk

csharp
using System;

public class Pine
{
    public static void Main()
    {
        string[] plants = { "leaf", "mint" };
        foreach (string plant in plants)
        {
            Console.WriteLine(plant);
        }
    }
}

Read it from the top. using System; prepares short names. public class Pine names the type. public static void Main() is where the runtime starts. string[] plants = { "leaf", "mint" }; stores two words. foreach (string plant in plants) walks them. Console.WriteLine(plant); writes each word. Two lines on the screen: leaf, then mint.

Run it with dotnet run. The program writes two lines and stops. It does not wait for you to type. If dotnet run waits, ReadLine is still in the file. Delete that line and keep the array plus the foreach above. The screen shows leaf, then mint. If the screen shows only leaf, you may still be on the arrays page that writes plants[0] once. Replace that with foreach. If the screen shows the letter plant on every line, the writing line has quotes: Console.WriteLine("plant");. If the screen shows foreach as letters, a writing line has quotes around that word. You do not reinstall the .NET SDK for a screen that shows the wrong lines.

Walk one full run in order. plants holds leaf, then mint. The first pass sets plant to leaf and the writing line writes leaf. The second pass sets plant to mint and writes mint. Then there are no more values, so the loop ends. You did not write int i = 0 or i < plants.Length on this page. The foreach header asks C# to visit each stored value once. The name plant is declared once in the header as string plant.

Walk an int array the same way

Change the stored array and the element type so each value is a whole number. Use int[] slots = { 2, 4, 6 }; and foreach (int n in slots) with Console.WriteLine(n); in the body. Now the screen should show three lines: 2, then 4, then 6. The word in still sits between the element name and the array name. The body still writes the name that holds one element.

int array walk

csharp
using System;

public class Pine
{
    public static void Main()
    {
        int[] slots = { 2, 4, 6 };
        foreach (int n in slots)
        {
            Console.WriteLine(n);
        }
    }
}

This is the second file. It is not the file you keep. Run dotnet run. The screen shows three lines. You replaced the string array with an int array and matched the element name’s type to int. After you have seen 2, 4, and 6, put the kept file back: plants with foreach (string plant in plants). Both versions are valid C#. They teach the same foreach shape with different element kinds.

Read the int run once more. slots holds 2, then 4, then 6. The first pass sets n to 2 and writes it. The second pass sets n to 4 and writes it. The third pass sets n to 6 and writes it. Then the loop ends. No quotes sit around the numbers in the array braces. Console.WriteLine(n) without quotes around n writes those stored numbers to the screen.

Rules that keep foreach clear

The parentheses must hold type, name, in, and array name in that order. Writing foreach (string plant plants) without in makes the build write an error. The element type must fit the array: string with a string array, int with an int array. Putting string plant beside an int[] array is not the shape this lesson builds. Braces still hold the body when the body has one or more lines.

foreach is not the counted for from the earlier page, and it is not break from the previous page. The counted for wrote start, test, and step with a counter. foreach walks values already stored in an array. break ends a loop early; this page’s first demo writes every value. Do not leave a break demo or a plain while in the same Main and wonder why the screen shows 1 and 2 instead of leaf and mint. This session’s Main should hold the array and the foreach only.

A common mix-up is writing the syntax itself: Console.WriteLine("foreach");. That writes the characters foreach. It does not walk the array. Another mix-up is Console.WriteLine("plant"); with quotes, which writes the letter word plant on every pass instead of leaf and mint. Keep Console.WriteLine(plant) without quotes when you want the element value on the screen.

If the array has no elements — for example string[] plants = { }; — the body never runs and the screen stays blank. That is still a valid foreach; this lesson’s demos keep at least two values so you can see the written lines. When you later need an index number on the screen, the counted for returns; foreach is for visiting values without managing that index yourself. Changing a value inside the loop with plant = "stem"; does not rewrite the array slot on this beginner shape — treat plant as the value you read for writing, not as a tool for editing plants.

You can now store an array, write foreach (Type name in arrayName), and write each value once. Matching the element type to the array keeps the loop building. The next page is methods, where you group lines under a name you can call from Main.

The screen is each array value

The file you keep writes leaf, then mint. The name plant is in the writing line, and the letters plant are not on the screen as a label. The word in is in the parentheses, and in is not on the screen. Quotes around plant or around foreach write letters, not the array walk.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
6
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top