tags:

views:

175

answers:

1

What is the way to convert the following into lambda expression?

ThreadPool.QueueUserWorkItem(delegate
     {
        Console.WriteLine("Current Thread Id is {0}:",
         Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("I will be used as Callback");
      }
    );
+2  A: 

You could definitely write this as a lambda expression:

// The underscore is simply a placeholder for the "state"
// parameter that the WaitCallback delegate expects - you could
// use any character but you must specify one as lamba expressions cannot
// omit parameters like anonymous functions can.
ThreadPool.QueueUserWorkItem((_) =>
    {
     Console.WriteLine("Current Thread Id is {0}:",
     Thread.CurrentThread.ManagedThreadId);
     Console.WriteLine("I will be used as Callback");
    });

But remember that a lambda expression has no meaning outside of your source code. The C# compiler will convert your lambda expression right back to the code you have now.

A lambda expression is simply syntactic sugar that you can use to express an anonymous function - the compiler will convert this to either an anonymous function or an expression tree.

Andrew Hare
Andrew ,what is the use of "_" (underscore) ?
oh! I got it as comment from your code.
Sorry, yes it's in the comment. Basically you need to throw *something* in there to be a placeholder.
Andrew Hare
The `(_) => ...` parameter would be more self-explanatory as `state => ...`.
Porges