← Back to C# Course | Chapter 8: Interfaces | Lesson 6 of 6

IEnumerable क्या है

IEnumerable यह promise है कि किसी चीज़ को एक-एक item करके चला जा सकता है। यह promise रखने वाली कोई भी चीज़ एक foreach loop में उपयोग की जा सकती है।

In this page:

  1. IEnumerable
Syntax
csharp
class ClassName : IEnumerable<type>
{
    public IEnumerator<type> GetEnumerator()
    {
        yield return item;
    }

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

IEnumerable

IEnumerable<T> वह interface है जो किसी type को इसके elements पर एक enumerator पाने का तरीका उजागर करके foreach loop में उपयोग करने योग्य बनाता है।

Arrays, List<T>, और Dictionary<K,V> सब इसे implement करते हैं। आप इसे किसी custom collection type पर खुद yield return का उपयोग करके lazily elements produce करने के लिए implement कर सकते हैं।

Note: IEnumerable<T> return करने वाले किसी method के अंदर yield return बिना manually IEnumerator implement किए एक iterator बनाता है।

उदाहरण: IEnumerable

markup
using System;
using System.Collections;
using System.Collections.Generic;

class Countdown : IEnumerable<int>
{
    private int start;
    public Countdown(int start) { this.start = start; }

    public IEnumerator<int> GetEnumerator()
    {
        for (int i = start; i >= 0; i--)
        {
            yield return i;
        }
    }

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

class Program
{
    static void Main(string[] args)
    {
        foreach (int n in new Countdown(3))
        {
            Console.WriteLine(n);
        }
    }
}
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. किसी collection को enumerate करते समय modify करना, जो InvalidOperationException फेंकता है।
  2. किसी lazy IEnumerable को कई बार enumerate करना और काम दोहराना।
  3. yield return भूल जाना और पूरी collection को एक साथ return करना।
चैप्टर सारांश
  • Interfaces एक contract define करते हैं जिसे classes implement करती हैं, और एक class कई interfaces implement कर सकती है।
  • Default interface methods optional implementations प्रदान करते हैं।
  • IComparable और IEnumerable sorting और iteration के लिए आम interfaces हैं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 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.