I have an interface that, among other things, implements a "public IEnumerator GetEnumerator()" method, so I can use the interface in a foreach statement.
I implement this interface in several classes and in one of them, I want to return an empty IEnumerator. Right now I do this the following way:
public IEnumerator GetEnumerator()
{
ArrayList arr = new ArrayList();
return arr.GetEnumerator();
}
However I consider this an ugly hack, and I can't help but think that there is a better way of returning an empty IEnumerator. Is there?
I was curious and went a bit further. I made a test that checks how efficient the methods are comparing
yield break
,Enumerable.Emtpy
and custom class.You can check it out on dotnetfiddle https://dotnetfiddle.net/vTkmcQ or use the code below.
The result of one of the many dotnetfiddle runs using 190 000 iterations was:
You can make a NullEnumerator which implements the IEnumerator interface. You can just pass an instance off the NullEnumerator.
here is an example of an EmptyEnumerator
The way I use is to use the enumerator of an empty array:
It can also be used for generic IEnumerator or IEnumerable (use an array of the appropriate type)
You could implement a dummy class that implements IEnumerator, and return an instance of it:
This is simple in C# 2:
You need the
yield break
statement to force the compiler to treat it as an iterator block.This will be less efficient than a "custom" empty iterator, but it's simpler code...
You can implement IEnumerator interface and IEnumerable, and return false from MoveNext function of IEnumerable interfase