🔁 C# Foreach Loop
The foreach
loop in C# provides a simple way to iterate through elements in a collection like arrays, lists, or any enumerable object. It’s ideal when you want to access each item in a sequence without using an index.
📘 Syntax
foreach (datatype item in collection)
{
// Code to execute for each item
}
💡 Why Use Foreach?
- Cleaner and safer than using a traditional
for
loop - No need to manage indexes or length
- Perfect for read-only access to each element
📄 C# Example: Foreach Loop
using System;
class Program
{
static void Main()
{
string[] fruits = { "Apple", "Banana", "Cherry", "Date" };
foreach (string fruit in fruits)
{
Console.WriteLine("Fruit: " + fruit);
}
}
}
📝 Sample Output
Fruit: Apple
Fruit: Banana
Fruit: Cherry
Fruit: Date
Fruit: Banana
Fruit: Cherry
Fruit: Date
📌 Key Points
foreach
automatically fetches each element in the sequence.- You can’t modify the collection directly inside a
foreach
. - It works with arrays, lists, dictionaries, and more.
Post a Comment