2
    static void Main(string[] args)
    {
        List<int> li = new List<int>() { 1, 20, 30, 4, 5 };
        GetNosLessThan5(li);
    }

    public static IEnumerable<int> GetNosLessThan5(List<int> numbers)
    {
        foreach (var v in numbers)
        {
            if (v < 5)
                yield return v;
        }
    }

I have put a debug point at the start of void main. When I press f11 continuously, the yellow arrow covers only the main function block and the debugging terminates. it never reaches the "getnoslessthan5" function at all.Confused.!

1 Answer 1

5

You're never actually iterating over the result, thus the actual body of the GetNosLessThan5 function is never executed. The compiler creates an iterator under the hood, but something needs to actually enumerate it for the function body to run.

See the MSDN Documentation about Iterators.

An iterator can be used to step through collections such as lists and arrays.

An iterator method or get accessor performs a custom iteration over a collection. An iterator method uses the Yield (Visual Basic) or yield return (C#) statement to return each element one at a time. When a Yield or yield return statement is reached, the current location in code is remembered. Execution is restarted from that location the next time the iterator function is called.

You consume an iterator from client code by using a For Each…Next (Visual Basic) or foreach (C#) statement or by using a LINQ query.

3
  • But sir inside main there is a call to the function right? so the function should be executed right. ?
    – callyaser
    Commented Feb 2, 2015 at 4:16
  • 1
    @callyaser No, you're calling a function that returns an IEnumerable - in other words, GetNosLessThan5 returns an object that says "I can be iterated over". It does not return the result of the enumeration - for that you'd have to call .ToList or a similar method that actually calculates the numbers. Iterators are a bit of compiler magic in C#. Commented Feb 2, 2015 at 4:18
  • (This is an optimization technique since Iterators can be expensive to run, or even infinite. It's the callers responsibility to decide if, when, and how long to run it) Commented Feb 2, 2015 at 4:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.