Question

I have a function that is passed to Select. But when I put a breakpoint in said function the program does not break.

Example:

public static int PlusTwo(int x)
{
  return x + 2;
}

public static void Main(string[] args)
{
  var foo = new[] { 2, 3, 5, 7 };
  var bar = foo.Select(PlusTwo);
}
Was it helpful?

Solution

That's because of the lazy evaluation. If you try doing a ToList(), the function would evaluate and the break-point would be hit - i.e. try doing:

var bar = foo.Select(PlusTwo).ToList();

OTHER TIPS

Enumerables are lazy evaluated.

This means that your function will not be called until you start to iterate over the result.

If you add:

for(var x in bar) ...

Then your function will be called.

If you want to get result immediately, call bar.ToArray() or bar.ToList(). This will internally iterate through the enumerable to create the result, which will ensure that the function is called.

You are using LINQ which has deferred execution. In other words it will not execute until you want the result of that operation. So if you had to do a foreach over it; it would then execute.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top