Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understand the following lambda

Tags:

c#

.net

I have a method like

void Test(Func<bool> f)
{
    f.Invoke();
}

I pass in the Test( ()=>GetItem("123") )

f.Invoke() actually called GetItem("123").

I want to know how does f know GetItem has a parameter?

like image 671
user496949 Avatar asked Apr 28 '26 11:04

user496949


2 Answers

Your function Test takes a function as a parameter. It will invoke whatever function is passed in as an argument.

In this case, when you create your lambda () => GetItem("123"), you are creating a function that takes no arguments, and invokes GetItem("123").

Test has no knowledge about the value of the parameter passed to GetItem, nor does it need to, because the value of the parameter is hardcoded in the lambda.

like image 130
Nader Shirazie Avatar answered May 01 '26 00:05

Nader Shirazie


You're question is a bit confusing. F doesn't know what's required by Getitem.

When you created the lambda, a "pointer" was returned to the place in the memory where a method is located. That method contains the line of code return Getitem("123"). When you invoke F, what actually happens is a kind of jump to a pointer. F is like a "pointer" to that place in the memory where the function is located.

So, to answer your question, F doesn't know what Getitem needs, F just calls the function your wrote, and that function has the "123" parameter hard coded.

Remember that lambda is a type of Delegate

like image 32
Neowizard Avatar answered May 01 '26 00:05

Neowizard



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!