36

What am I doing wrong here? How can I execute my action?

var recurse = new Action<IItem, Int32>((item, depth) =>
{
    if (item.Items.Count() > 0) recurse(item, depth + 1); // red squiggly here

    // ...
});

I'm getting a red squiggly when calling recurse saying "method, delegate or event expected".


Update

I've accepted Homam's answer. I'd just like to add/share another syntax for the same... But which I find a bit easier on the eyes...

Action<IEnumerable<Item>> Recurse = null;

Recurse = item =>
{
    if (item.Items != null) Recurse(item.Items);

    // ...
};
dharmatech
  • 8,979
  • 8
  • 42
  • 88
cllpse
  • 21,396
  • 37
  • 131
  • 170

1 Answers1

62

Just define the delegate Action and assign null to it before calling it recursively.

Action<IItem, Int32> recurse = null;

Then

recurse = new Action<IItem, Int32>((item, depth ) =>
{
    if (item.Items.Count() > 0) recurse(item, depth + 1); // red squiggly here
    // ...
});

Good luck!

Homam
  • 23,263
  • 32
  • 111
  • 187
  • I'd hate to have to split definition and implementation. Is there any way I can do this in one line of code? – cllpse Oct 26 '10 at 14:21
  • 6
    No. Eric explains why in his blog entry (per usual it appears): http://blogs.msdn.com/b/ericlippert/archive/2006/08/18/706398.aspx – Ron Warholic Oct 26 '10 at 14:28
  • @Ron: Nice tidbit. Makes some sort of weird sense :) – cllpse Oct 26 '10 at 14:50
  • There are ways to do anonymous recursion, such as defining a Y-Combinator, but this is much simpler. See http://blogs.msdn.com/b/wesdyer/archive/2007/02/02/anonymous-recursion-in-c.aspx – mbeckish Oct 26 '10 at 15:19
  • And the comments on Eric's blog have a fixed-point combinator that allows you to implement the lambda at the point of declaration, with no split. – Ben Voigt Oct 26 '10 at 15:21
  • Updated blog link - https://learn.microsoft.com/en-us/archive/blogs/ericlippert/why-does-a-recursive-lambda-cause-a-definite-assignment-error – Bondolin Jun 30 '20 at 19:04