Misko
Misko

Reputation: 2044

Breakpoint not hit when method called in lambda

When I put a breakpoint in a method I'm calling from a lambda expression, the breakpoint is never hit. When I move the method call outside the lambda, the breakpoint hits.

For example:

Function IncrementAll(ByVal items As IEnumerable(Of Integer)) As IEnumerable(Of Integer)
  Return items.Select(Function(i) Increment(i))
End Function

Function Increment(ByVal i As Integer) As Integer
  Return i + 1 'Breakpoint here
End Function

If I call IncrementAll, the breakpoint in Increment does not get hit. Is there a way to make VS 2008 stop on these breakpoints? I hate the thought of rewriting all my LINQ into loops just for debugging.

Upvotes: 2

Views: 1923

Answers (1)

w.brian
w.brian

Reputation: 17407

So, I figured it out. The Select returns an IEnumerable, and the actual execution of Increment on each item is deferred until you try to access an item in the IEnumerable. The quickest way to get the desired effect would be this:

Function IncrementAll(ByVal items As IEnumerable(Of Integer)) As IEnumerable(Of Integer)
    Return items.Select(Function(i) Increment(i)).ToList()
End Function

The ToList() immediately enumerates, thus executing Increment on each element, and your breakpoint will fire.

Upvotes: 4

Related Questions