Is there a case where delegate syntax is preferred over lambda expression for anonymous methods?

前端 未结 7 1526
别跟我提以往
别跟我提以往 2021-02-07 21:13

With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have

7条回答
  •  攒了一身酷
    2021-02-07 21:54

    One not so big advantage for the older delegate syntax is that you need not specify the parameters if you dont use it in the method body. From msdn

    There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions.

    For example you can do:

    Action a = delegate { }; //takes 1 argument, but not specified on the RHS
    

    While this fails:

    Action a = => { }; //omitted parameter, doesnt compile.
    

    This technique mostly comes handy when writing event-handlers, like:

    button.onClicked += delegate { Console.WriteLine("clicked"); };
    

    This is not a strong advantage. It's better to adopt the newer syntax always imho.

提交回复
热议问题