callyaser
callyaser

Reputation: 155

Why breakpoint is not reached in VisualStudio 2010?

    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.!

Upvotes: 2

Views: 116

Answers (1)

Michael Stum
Michael Stum

Reputation: 180874

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.

Upvotes: 5

Related Questions