IEnumerator in Dotnet
`IEnumerator` is an interface provided by the .NET framework, primarily used for iterating through collections of objects. It defines methods for iterating over a collection in a forward-only, read-only manner. The `IEnumerator` interface is part of the System.Collections namespace.
Here's the basic structure of the `IEnumerator` interface:
csharp
public interface IEnumerator
{
bool MoveNext();
void Reset();
object Current { get; }
}
- `MoveNext()`: Advances the enumerator to the next element of the collection. It returns `true` if there are more elements to iterate; otherwise, it returns `false`.
- `Reset()`: Resets the enumerator to its initial position before the first element in the collection.
- `Current`: Gets the current element in the collection. This is an object because `IEnumerator` is not type-specific.
Implementing IEnumerator:
You can implement the `IEnumerator` interface in your custom collection classes to enable them to be iterated using `foreach` loops.
Here's an example of a custom collection that implements the `IEnumerator` interface:
```csharp
public class CustomCollection : IEnumerable, IEnumerator
{
private object[] _items;
private int _currentIndex = -1;
public CustomCollection(object[] items)
{
_items = items;
}
public IEnumerator GetEnumerator()
{
return this;
}
public bool MoveNext()
{
_currentIndex++;
return _currentIndex < _items.Length;
}
public void Reset()
{
_currentIndex = -1;
}
public object Current
{
get
{
try
{
return _items[_currentIndex];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
In this example, `CustomCollection` implements both `IEnumerable` and `IEnumerator`. The `GetEnumerator` method returns the current object as the enumerator, and `MoveNext`, `Reset`, and `Current` methods are implemented to fulfill the `IEnumerator` contract.
Usage of `IEnumerator` allows you to create custom collections that can be iterated in a `foreach` loop, providing a consistent and familiar way to work with your data structures. When implementing `IEnumerator`, be mindful of the iteration state, especially after reaching the end of the collection.
No comments:
Post a Comment
Comments Welcome