views:

141

answers:

4

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?

+7  A: 
public IEnumerable<int> Iterator {
    get { yield break; }
}
Mehrdad Afshari
my new favorite
Will
+2  A: 

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>(); }
}
JaredPar
impressive. Much better than `yield break;`. Yes, I'm being sarcastic.
Will
+5  A: 

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

Konrad Rudolph
yerp this is my favorite by far
Sam Saffron
But ... its only available with .Net 3.5
Sam Saffron
A: 

public IEnumerable Iterator { get { yield break; } }

Levon