2

Sorry if this is obvious. I'm trying to make the jump from VB.NET to C# and I'm currently playing around with tasks. In VB.NET I can define a task like so:

    Dim t As New Task(Sub()
                          Threading.Thread.Sleep(1000)
                      End Sub)

The part after task makes sense to me, I'm creating a new method.

In C# it looks like:

        Task t = new Task(() =>
            {
                Thread.Sleep(1000);
            });

I'm guessing the () is stating it's a new method but what is and why do I need =>.

GJKH
  • 1,715
  • 13
  • 30
  • @BenReich my bad, I did search first but didn't come up with this. Still though, the `=>` seems superfluous but that's probably because I've only ever worked with vb.net – GJKH May 24 '13 at 23:41
  • The () indicate the argument list for the method. In this case, you don't have any arguments, but you need to the parenthesis anyway – Walt Ritscher May 25 '13 at 06:21
  • 1
    I don't think anyone has answered "why" - I think it's required to eliminate any possible ambiguity in the parsing of C# code (this was probably also the reason "delegate" was used in 'legacy' C# code). – Dave Doknjas May 25 '13 at 23:28

3 Answers3

9

The => is the syntax used by C# to define a lambda expression.

It is the equivelent of the Sub() / End Sub in your VB Task constructor.

Instead of defining a delegate as:

Dim del as Action = Sub() Threading.Thread.Sleep(1000)

In C#, you would write:

Action del = () => Threading.Thread.Sleep(1000);

The Task just moves this same syntax into the constructor, and declares it inline.

Walt Ritscher
  • 6,977
  • 1
  • 28
  • 35
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
1

That example is creating the task using a lamda expression for the function definition. You could also create it using a delegate or a pre-defined function like this:

void MyFunction() {
  Thread.Sleep(1000);
}

and creating your Task like this:

Task t = new Task(MyFunction);

Please see the following link for more information on lamda expressions:

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

Shawn Lehner
  • 1,293
  • 7
  • 14
1

If you like, you can use this equivalent syntax:

Task t = new Task(delegate()
{
    Thread.Sleep(1000);
});

But in C# people pretty much always use the lambda syntax.

Timothy Shields
  • 75,459
  • 18
  • 120
  • 173