Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is => operator in this code

Tags:

operators

c#

I am using ThreadPool with the follwoing code:-

ThreadPool.QueueUserWorkItem
                (o =>
                MyFunction()
                );

I am not sure what does o=> does in this code. Can anyone help me out.

like image 535
Zeeshan Umar Avatar asked Jun 28 '10 04:06

Zeeshan Umar


2 Answers

It describes a lambda (anonymous) function. In this case it's a function that takes one argument, o, and then executes MyFunction (although in this case it's basically throwing the value of o away). It's equivalent to:

void Foo(object o) //We know that Foo takes an object and returns void because QueueUserWorkItem expects an instance of type WaitCallback which is a delegate that takes and object and returns void
{
  MyFunction();
}

ThreadPool.QueueUserWorkItem(Foo) // or ThreadPool.QueueUserWorkItem(new WaitCallback(Foo));

The type of o is inferred based on whatever QueueUserWorkItem expects. QueueUserWorkItem expects type WaitCallback so in this case o should be of type object because WaitCallback is delegate for methods with one parameter of type object that return void.

As for the meaning of this particular code fragment; you're basically adding a function (work item) to a queue that will be executed by one of the threads in the pool (when it becomes available). That particular code fragment just describes a nice, succinct way of passing in the function without having to go through the trouble of fully defining a class method.

Incidentally, I, and others, tend to read => as 'such that'. Some people read it as 'goes to'.

like image 130
Rodrick Chapman Avatar answered Oct 03 '22 21:10

Rodrick Chapman


This is the C# syntax for a lambda expression.

  • http://msdn.microsoft.com/en-us/library/bb397687.aspx

It is in many ways an inline delegate definition. It saves you the tediousness of defining an extra function to use as the delegate target.

private object Target(object state) {
  MyFunction();
}

...
ThreadPool.QueueUserWorkItem(new WaitCallback(Target));
like image 40
JaredPar Avatar answered Oct 03 '22 20:10

JaredPar