Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the lambda to reference itself

Tags:

c#

lambda

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)

like image 606
KugBuBu Avatar asked Sep 16 '14 19:09

KugBuBu


Video Answer


2 Answers

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;
like image 71
Servy Avatar answered Oct 11 '22 08:10

Servy


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);
like image 26
TehPers Avatar answered Oct 11 '22 07:10

TehPers