I have a general question: in the C# code below thread tFour
can not be created and the compiler shows me the following error: "Anonymous function converted to a void returning delegate cannot return a value"
THE CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DelegatesAndLambda
{
class Program
{
public static int ThrowNum(object a)
{
Console.WriteLine(a);
return 2 * (int)a;
}
static void Main(string[] args)
{
Func<int> newF = delegate () { int x = ThrowNum(2); return x; };
Thread tOne = new Thread( delegate () { int x = ThrowNum(2); });
Thread tTwo= new Thread(()=> ThrowNum(2));
Thread tThree = new Thread(() => newF());
Thread tFour = new Thread(delegate () { int x = ThrowNum(2); return x;});
}
}
}
However, threads tOne
, tTwo
and tThree
are created without an error. So why does the lambda expression allows to pass a method delegate with return (non-void) value and multiple parameters (ThrowNum(2), newF()
) while an anonymous method with return value ( delegate () { int x = ThrowNum(2); return x;}
) defined using the delegate keyword can not be passed? I thought in both cases we deal with anonymous methods? I do know that Thread
accepts only two types of signatures : void DoSomething()
and void DoSomething(object o)
but what is the major difference between initializations of tTwo
and tFour
using the same(?) anonymous method? I have been trying to find answer for a while but did not succeed.
Thanks