In C#, IEnumerable
is an interface that defines a standard way for classes to represent a sequence of objects that can be iterated over. This interface defines a single method, GetEnumerator
, which returns an IEnumerator
object that can be used to iterate over the elements of the sequence. Classes that implement IEnumerable
can be used with the foreach
statement in C# to iterate over the elements in the sequence.
For example,
// Define a class that implements IEnumerable<int>
class MyList: IEnumerable < int > {
private List < int > _items = new List < int > ();
public void Add(int item) {
_items.Add(item);
}
// Implement the GetEnumerator method from IEnumerable<int>
public IEnumerator < int > GetEnumerator() {
return _items.GetEnumerator();
}
// This method is required by IEnumerable, but it's not used in this example
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
throw new NotImplementedException();
}
}
// Use the MyList class with the foreach statement
MyList list = new MyList();
list.Add(1);
list.Add(2);
list.Add(3);
foreach(int item in list) {
Console.WriteLine(item);
}
In the above example, the MyList
class implements the IEnumerable<int>
interface, which allows it to be used with the foreach
statement to iterate over the items in the list. The MyList
class defines an Add
method for adding items to the list, and it implements the GetEnumerator
method from IEnumerable<int>
to return an IEnumerator
object that can be used to iterate over the items in the list.