Sam Saffron
Sam Saffron

Reputation: 131122

Implementing empty iterators

I have this code:

    public IEnumerable<int> Iterator {
        get { if (false) yield return -1; }
    }

It is fairly ugly, but when you try to refactor it to:

    public IEnumerable<int> Iterator {
        get { return null; }
    }

The following code breaks:

foreach (var item in obj.Iterator) {
}

How would you go about cleaning this up?

Upvotes: 0

Views: 360

Answers (4)

Levon
Levon

Reputation: 1

  public IEnumerable<int> Iterator {
        get { yield break; }
    }

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 545875

The .NET framework already has a method to do exactly this, by the way (making Jared's code redundant): System.Enumerable.Empty<T>.

Upvotes: 6

JaredPar
JaredPar

Reputation: 755141

A better solution would be to define a reusable method for this problem. I keep a method around in my shared library to take care of just this case.

public static class CollectionUtility { 
  public static IEnumerable<T> CreateEmptyEnumerable<T>() {
    yield break;
  }
}

Now in your method you could just call

public static IEnumerable<int> Iterator { 
  get { return CollectionUtility.CreateEmptyEnumerable<int>(); }
}

Upvotes: 2

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422112

public IEnumerable<int> Iterator {
    get { yield break; }
}

Upvotes: 10

Related Questions