Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invokes and Delegates in C#

Can someone explain the syntax in this block of code?

Invoke((MethodInvoker)
    (
        () => 
        {
            checkedListBox1.Items.RemoveAt(i);
            checkedListBox1.Items.Insert(i, temp);
            checkedListBox1.Update();
        }
    )
);

I'm using a backgroundworker which needs to update parts of the UI so I used this. It works, but I don't know what the empty () and => mean.

like image 547
Jack Avatar asked Dec 31 '25 07:12

Jack


1 Answers

() and => is a lambda expression.

Action a = () => { 
    //code here
}

is a delegate of type Action, which executes the code in the block.

Func<string> f = () => {
    //code here
    return "string";
}

is a delegate of type Func<string>, which executes the code in the block and then returns a string.

Func<int, int, string> f = (i, j) => {
    //code here
    return "string"+i+j;
}

is a delegate of type Func<int, int, string>, which has two int parameters referred to i and j in the code block and returns a string.

Etc...

like image 99
Petar Ivanov Avatar answered Jan 01 '26 21:01

Petar Ivanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!