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?
Empty<T> method returns an empty enumerable which doesn't yield any values when being enumerated. Enumerable. Empty<T> comes in very handy when you want to pass an empty to collection to a method accepting a parameter of type IEnumerable<T> . We can see that the returned sequence is an (empty) array of integers.
Empty<T> actually returns an empty array of T (T[0]), with the advantage that the same empty array is reused. Note that this approach is not ideal for non-empty arrays, because the elements can be modified (however an array can't be resized, resizing involves creating a new instance).
Clear() will empty out an existing IEnumerable. model. Categories = new IEnumerable<whatever>() will create a new empty one. It may not be a nullable type - that would explain why it can't be set to null.
This is simple in C# 2:
public IEnumerator GetEnumerator() { yield break; }
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...
There is an extra function in the framework:
public static class Enumerable { public static IEnumerable<TResult> Empty<TResult>(); }
Using this you can write:
var emptyEnumerable = Enumerable.Empty<int>(); var emptyEnumerator = Enumerable.Empty<int>().GetEnumerator();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With