Reputation: 131122
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
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
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
Reputation: 422112
public IEnumerable<int> Iterator {
get { yield break; }
}
Upvotes: 10