tags:

views:

60

answers:

1

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

+5  A: 

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
I'd hate to have to split definition and implementation. Is there any way I can do this in one line of code?
roosteronacid
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
@Ron: Nice tidbit. Makes some sort of weird sense :)
roosteronacid
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
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