Why can't I define an action in a string in a method waiting for a delegate?

Given the following sample MSDN code, why can't I define an Action "inline" delegate:

public static void Main(string[] args) { Action someAction = () => Console.WriteLine("Hello from the thread pool!"); Task.Factory.StartNew(someAction); } 

... so inline, like:

 public static void Main(string[] args) { Task.Factory.StartNew(Action someAction = () => Console.WriteLine("etc.")); } 

Thanks,

Scott

+7
delegates action
source share
4 answers

Invalid C #:

 public static void Main(string[] args) { Task.Factory.StartNew(Action someAction = () => Console.WriteLine("etc.")); } 

Do this instead:

 public static void Main(string[] args) { Task.Factory.StartNew(() => Console.WriteLine("etc.")); } 
+13
source share

You are trying to delegate a variable in a method call. Just deleting a variable declaration can be wonderful:

 public static void Main(string[] args) { Task.Factory.StartNew(() => Console.WriteLine("etc.")); } 

Here, the Action not derived from the lambda expression itself, but from the method that it is trying to do. Normal overload resolution is performed, and the compiler tries to convert the lambda expression to the appropriate parameter type. If the parameter type was just Delegate (e.g. Control.Invoke ) then the output type failed because the compiler would not have any specific target types to try to convert.

If this does not work (I cannot easily check its atm), you just need to specify to indicate which type of delegate the lambda expression should be converted:

 public static void Main(string[] args) { Task.Factory.StartNew((Action)(() => Console.WriteLine("etc."))); } 

Honestly, at this point I would prefer to see a separate variable in terms of readability.

+4
source share

You include an ad operator that is not a legal expression. Try:

 Task.Factory.StartNew(() => Console.WriteLine("etc.")); 

If you call an API where the delegate type cannot be inferred, you can explicitly use translation or call the delegate constructor:

 Task.Factory.StartNew((Action)(() => Console.WriteLine("etc."))); Task.Factory.StartNew(new Action(() => Console.WriteLine("etc."))); 
+2
source share

I would not know tbh, but I think you can do:

 public static void Main(string[] args) { Task.Factory.StartNew(delegate() {Console.WriteLine("etc.");}); } 
+1
source share

All Articles