Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Func type with a parameter and void return

I wanted to know why this doesn't work ? The compiler says that void cannot be used with Func type. In that case what are my options

  Func<int,void> func1 =  (x) => { Console.WriteLine("Hello World"); };
like image 458
MistyD Avatar asked Dec 18 '25 21:12

MistyD


2 Answers

Func<T, TResult> delegate has one parameter and returns a value of the type specified by TResult, you can't use void, because it specifies that method doesn't return any value and can't be used as type argument.

You can use Action<T> delegate in your example, it has a single parameter and doesn't return a value

Action<int> action = (x) => { Console.WriteLine("Hello World"); };

Since x parameter isn't used, you can just use parameterless Action delegate

Action action = delegate { Console.WriteLine("Hello World"); };
like image 196
Pavel Anikhouski Avatar answered Dec 21 '25 13:12

Pavel Anikhouski


You are looking for Action<int>

like image 29
Marc Gravell Avatar answered Dec 21 '25 14:12

Marc Gravell



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!