What is the purpose of empty parentheses in a lambda statement?

Asked

Viewed 469 times

11

I created an example of a Lambda statement with no arguments, however, I have doubts regarding the omission of the empty parenthesis () in the statement.

Take the example:

class Program
{
    public delegate void MyDelegate();

    static void Main(string[] args)
    {
        MyDelegate d = () => 
                            {
                                Console.WriteLine("Ola mundo lambda! :]");
                            };
        d();

        Console.ReadKey();
    }
}

My doubts are as follows.

  1. What is the purpose of empty parentheses ()?
  2. And what he implies in the statement?
  3. It assumes the behavior of a variable?
  • 2

    From what I understand from explanation by @utluiz, means there’s no parameter being passed.

1 answer

13


It is to indicate that the anonymous function it represents has no parameter. It was the way you arranged for the syntax not to be lame, since you always have to have something before the => which separates the parameters from the body of the function.

There’s nothing different from the others Amble.

In theory they could leave without, but it gets weird and could create some ambiguity in the future, if it is that already does not have and I did not realize. Design language requires good taste and thinking about the future.

Think of the common function, normally it would have parentheses always, having a parameter or not. Why a lambda don’t need to? Well, because it is a convenience syntax, the less write better (and it is not because of typing, it is to give more legibility even, and go straight to the point). So she avoids parentheses whenever possible, this is not a possible case.

Another case where they are needed is when you have more than one parameter. So convenience is only for one parameter, which is the most commonly used case.

I didn’t need the keys.

MyDelegate d = () => Console.WriteLine("Ola mundo lambda! :]");

I put in the Github for future reference.

Look how weird, but you could have accepted it like this:

MyDelegate d = => Console.WriteLine("Ola mundo lambda! :]");

Imagine the person forgetting the space between the two =.

  • Could have used the void I think it would make more sense in the code: MyDelegate d = void => Console.WriteLine("Ola mundo lambda! :]");

  • 1

    They could, but I don’t think it has a C#face, which even wants to be closer to the functional languages they use like this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.