Nested functions with recursion

2.8k views Asked by At

I've looked at a ton of references and have seen that C# supports nested functions through lambda, but I'm completely new to C# (and .NET for that matter). I want to write a flood-fill implementation, with the parameters of a parent function accessible to the nested child.

Here's what it should look like, ideally:

private void StartFloodFill(color,otherstuff,pixel)
{
      function Recursion(pixel,color)
      {
             do(otherstuff);
             //etc...
             Recursion(pixel,color);
      }
}

The Recursion(pixel,color); call is where my confusion lies. I can't access a reference to the function from inside the function.

I know there should be a workaround for this, but I don't know what that is. How can I implement a recursive function like that demonstrated above in C#?

1

There are 1 answers

1
dcastro On BEST ANSWER

As suggested, you can use a recursive delegate. Normally, you'd declare a delegate like this:

Func<int,int, int> = (a, b) => a+b;

Where Func<int, int, int> is the type of a delegate that takes 2 ints, and returns another int.

But since you want to make it call itself, you have to declare the variable before assigning the delegate.

Func<Pixel, Color, SomeType> func = null;

func = (pixel, color) => {
    //do stuff...

    if(endCondition)
       return someTypeValue;
    else
       return func(pixel, color);
};