I understand Lambda expressions in the sense of:
delegate int del(int i);
static void Main()
{
del myDelegate = x => x * x;
int j = myDelegate(2);
Console.WriteLine(j);
Console.ReadLine();
}
It's actually quite neat, and something I will use again, however I read this:
static void Main()
{
Thread t = new Thread(() => Print("Hello from t!"));
t.Start();
Console.ReadKey();
}
static void Print(string message)
{
Console.WriteLine(message);
}
I can't quite figure out what () =>
means, after googling I found out that I am (according to wikipedia) using an anonymous function that is undefinded (?) and/or not bound to an identifier.
Now, I ask what does that mean? Am I even doing what I just stated?
() =>
is the start of a lambda expression that doesn't have any parameters. It's important to understand that a lambda expression can't exist in a vacuum - it's always part of a conversion to either a delegate type or an expression tree type.
In this case, this is being used as an argument to the Thread
constructor.
If you look at the thread constructor, there are four overloads, two of which have a single parameter. One takes a ThreadStart
parameter, the other takes a ParameterizedThreadStart
parameter. These are both delegate types, but ParameterizedThreadStart
has a parameter whereas ThreadStart
doesn't.
So there's an implicit conversion from your parameterless lambda expression to ThreadStart
, but not to ParameterizedThreadStart
, so it will call the overload taking a ThreadStart
.
So it's equivalent to:
ThreadStart tmp = () => Print("Hello from t!");
Thread t = new Thread(tmp);
To use a ParameterizedThreadStart
, there are three options:
// x is inferred to be type object
ParameterizedThreadStart tmp = x => Print("Hello from t!");
// The same, but with brackets around the parameter
ParameterizedThreadStart tmp = (x) => Print("Hello from t!");
// Fully explicit parameter list
ParameterizedThreadStart tmp = (object x) => Print("Hello from t!");
(Again, these could be inlined into the Thread
constructor call, and the compiler would infer which constructor was intended.)
See more on this question at Stackoverflow