Frage

In the following code, I understand the second initialization prints one "outside" and three "inside". But why does the first does not print at all, I expect it to print one "outside".

        DeferExecution a = new DeferExecution(); // prints nothing 
        DeferExecution b = new DeferExecution(null); // print one "outside" and three "inside".

 class DeferExecution
{
    public IEnumerable<string> Input;

    public DeferExecution()
    {
        Input = GetIEnumerable();
    }

    public DeferExecution(string intput)
    {
        Input = GetIEnumerable().ToArray();
    }

    public IEnumerable<string> GetIEnumerable()
    {
        Console.WriteLine("outside");  
        var strings = new string[] {"a", "b", "c"};
        foreach (var s in strings)
        {
            Console.WriteLine("inside");  
            yield return s;
        }
    }
}
War es hilfreich?

Lösung

The enumerable returned is implemented as an iterator block (i.e., a method that uses yield).

Code inside iterator blocks does not actually execute until they are enumerated for the first time, so you won't see anything happen if you don't actually do anything with the IEnumerable.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top