IEnumerable Interface in C#
IEnumerable in C# is an interface that defines a standard way to iterate over a collection of objects. It provides a simple and efficient mechanism to access elements within a sequence, one at a time. It is used to define a collection that can be enumerated, meaning it can be iterated over using a foreach loop or other iteration constructs.
The IEnumerable<T> interface provides a single method, GetEnumerator(), which returns an enumerator that can be used to iterate through the collection.
public interface IEnumerable<out T> : IEnumerable
{
IEnumerator<T> GetEnumerator();
}
Now let's see what is IEnumerator<T>.
public interface IEnumerator<out T> : IDisposable, IEnumerator
{
T Current { get; }
}
It contains an abstract property named Current, which returns the element in the collection at the current position of the enumerator.
Here, you can see that IEnumerator<T> extends the IEnumerator interface. The nongeneric version of the IEnumerator interface contains two abstract methods.
public interface IEnumerator
{
bool MoveNext();
object Current { get; }
void Reset();
}
- bool MoveNext(): Advances the enumerator to the next element of the collection. It returns true if the enumerator was successfully advanced to the next element and false if the enumerator has passed the end of the collection.
- void Reset(): Sets the enumerator to its initial position, which is before the first element in the collection.
Now, let's create a List<int> with some random values and assign it to an IEnumerable<int> reference variable.
IEnumerable<int> numbers = new List<int>{1,2,3,4,5};
The List<T> class implements IEnumerable<T>, enabling us to iterate over its elements using a foreach loop. This allows for polymorphic behavior, where a List<T> object can be assigned to an IEnumerable<T> reference variable.
Here, let me explain how a foreach loop works. Behind the scenes, the foreach loop code looks like this
var enumerator = numbers.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
var enumerator = numbers.GetEnumerator()
- This code calls the GetEnumerator method on the number's collection, which returns an enumerator that can be used to iterate through the collection.
while (enumerator.MoveNext())
- This code starts a while loop that continues as long as MoveNext returns true.
- The MoveNext method advances the enumerator to the next element of the collection.
- If the enumerator successfully moves to the next element, it returns true; otherwise, it returns false.
Console.WriteLine(enumerator.Current)
- This code writes the current element of the collection to the console. The Current property of the enumerator gets the element in the collection at the current position of the enumerator.
Output
By understanding IEnumerable, you can effectively work with collections in C#, write more efficient and readable code, and take advantage of the powerful features of LINQ.
Happy Coding!!!