Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return an empty IEnumerator

Tags:

c#

ienumerator

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?

like image 220
David Božjak Avatar asked Nov 11 '09 10:11

David Božjak


People also ask

How do I return an empty enumerable?

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.

How do I return an empty IEnumerable list in C#?

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).

How do I empty my IEnumerable?

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.


2 Answers

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...

like image 140
Jon Skeet Avatar answered Sep 21 '22 14:09

Jon Skeet


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(); 
like image 29
user287107 Avatar answered Sep 24 '22 14:09

user287107