What is the purpose of an empty parenthesis in a Lambda declaration?

9

I created an example of a Lambda declaration with no arguments, however, I am in doubt about omission of the empty parenthesis () in the declaration.

See 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.

  • What is the purpose of empty parentheses () ?
  • And what does it entail in the statement?
  • Does it assume the behavior of a variable?
  • asked by anonymous 23.06.2016 / 00:34

    1 answer

    10

    It is to indicate that the anonymous function it represents does not have any parameters. It was the way it was arranged for the syntax not to get stuck, since you always have to have something before the => that separates the body parameters from the function.

    There is nothing different about the other lambdas .

    In thesis could leave without, but it gets weird and could create some ambiguity in the future, if it does not already have and I did not realize. Design of 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 does a lambda not need? Well, because it's a convenience syntax, the less you write better (and it's not even typing, it's to give you more legibility, and get right to the point). So she avoids parenthesis whenever possible, this is not a possible case.

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

    You did not need the keys.

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

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

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

    Imagine the person forgetting the space between the two = .

        
    23.06.2016 / 01:34