Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

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>(); }
}
  public IEnumerable<int> Iterator {
        get { yield break; }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top