← Back to C# Course | Chapter 4: Control Flow | Lesson 6 of 7

foreach Loop कैसे लिखें

एक foreach loop किसी collection के हर item को एक-एक करके visit करता है, जैसे एक teacher किसी row में हर student को एक sheet दे रही हो। आपको कभी positions गिनने की ज़रूरत नहीं।

In this page:

  1. foreach Loop
Syntax
csharp
foreach (type item in collection)
{
    // use item
}

foreach Loop

foreach बिना manual index tracking के किसी collection के हर element पर iterate करता है, IEnumerable implement करने वाली किसी भी type के साथ काम करते हुए।

यह arrays, lists, और दूसरी collections को process करने का सबसे सुरक्षित और readable तरीका है। आप items skip करने के लिए loop variable को modify नहीं कर सकते — उसके लिए indexed access उपयोग करें।

Note: जब आपको index की ज़रूरत न हो तो for से foreach को प्राथमिकता दें।

उदाहरण: foreach Loop

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        string[] fruits = { "apple", "banana", "cherry" };

        foreach (string fruit in fruits)
        {
            Console.WriteLine(fruit);
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी foreach के अंदर collection को modify करना, जो InvalidOperationException फेंकता है।
  2. loop variable को assign करने की कोशिश करना, जो foreach में read-only है।
  3. किसी null collection पर foreach उपयोग करना, जो NullReferenceException फेंकता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.