KugBuBu
KugBuBu

Reputation: 630

Get the lambda to reference itself

I am trying to make lambda able to reference to itself, an example:

PictureBox pictureBox=...;
Request(() => {
    if (Form1.StaticImage==null)
        Request(thislambda); //What to change to the 'thislambda' variable?
    else
        pictureBox.Image=Form1.StaticImage; //When there's image, then just set it and quit requesting it again
});

When I tried to put the lambda in variable, while the lambda referenced to itself, error of course.

I thought about creating class with a method that able to call itself, but I want to stick here with lambda. (While it gives only readibility so far and no advandges)

Upvotes: 11

Views: 3798

Answers (3)

TehPers
TehPers

Reputation: 316

As of C# 7, you can also use local functions:

PictureBox pictureBox=...;
void DoRequest() {
    if (Form1.StaticImage == null)
        Request(DoRequest);
    else
        pictureBox.Image = Form1.StaticImage; //When there's image, then just set it and quit requesting it again
}

Request(DoRequest);

Upvotes: 4

Vikas Gupta
Vikas Gupta

Reputation: 4465

Here is an interesting post on the subject from the experts - http://blogs.msdn.com/b/wesdyer/archive/2007/02/02/anonymous-recursion-in-c.aspx

Excerpt from the post - "A quick workaround is to assign the value null to fib and then assign the lambda to fib. This causes fib to be definitely assigned before it is used.

Func<int, int> fib = null;
fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;
Console.WriteLine(fib(6)); // displays 8

But our C# workaround doesn't really use recursion. Recursion requires that a function calls itself."

Read the entire post, if you are looking for other fun ways of doing it.

Upvotes: 0

Servy
Servy

Reputation: 203829

You need to declare the delegate, initialize it to something so that you are not accessing an uninitialized variable, and then initialize it with your lambda.

Action action = null;
action = () => DoSomethingWithAction(action);

Probably the most common usage I see is when an event handler needs to remove itself from the event when fired:

EventHandler handler = null;
handler = (s, args) =>
{
    DoStuff();
    something.SomeEvent -= handler;
};
something.SomeEvent += handler;

Upvotes: 30

Related Questions