Is it possible to declare a general delegate without parameters?

I have...

Func<string> del2 = new Func<string>(MyMethod); 

and I really want to do this.

 Func<> del2 = new Func<>(MyMethod); 

therefore, the return type of the callback method is invalid. Is this possible with the generic func type?

+4
source share
4 answers

The Func delegate family is for methods that take zero or more parameters and return a value. For methods that take zero or more parameters, do not return a value using one of the Action delegates. If the method has no parameters, use the non-generic version of Action :

 Action del = MyMethod; 
+13
source

Yes the function returning void (no value) is Action

 public Test() { // first approach Action firstApproach = delegate { // do your stuff }; firstApproach(); //second approach Action secondApproach = MyMethod; secondApproach(); } void MyMethod() { // do your stuff } 

hope this helps

+7
source
+3
source

In cases where you forcefully use Func<T> , for example. in the internal general API that you want to reuse, you can simply define it as new Func<object>(() => { SomeStuff(); return null; }); .

+2
source

Source: https://habr.com/ru/post/1385099/


All Articles