Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Lambda with no inputs (params)?

Tags:

c#

lambda

I was just wondering about this case

void exc(Func<int> fn) {
    fn();
}

I can do the below

public void test() {
    exc(delegate{return 1;});
}

However I like the => syntax so i tried

public void test() {
    exc(void=>1);
}

It didnt compile. Is there a way I may use the => syntax?


2 Answers

You almost did from the top of your head :). Check MSDN for more details, but this is what you are looking for:

public void test()
{
    exc(()=>1);
}
like image 126
bas Avatar answered May 08 '26 02:05

bas


Func<int> means a function that takes no arguments and returns an integer. So you could specify it as an anonymous function like this

public void test()
{
    exc(() => 1);
}
like image 38
Darin Dimitrov Avatar answered May 08 '26 03:05

Darin Dimitrov



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!