How does anonymous methods omit parameter list? [closed]
Asked Answered
D

1

6

I was reading this in the MSDN documentation on Anonymous Methods (C# Programming Guide), but I do not understand the part about omitting the parameter list. It says:

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.

Could you provide an example of ommiting a parameter list for an anonymous method?

Draper answered 7/4, 2014 at 21:6 Comment(3)
See a lot of other threads, fpr example delegate keyword vs. lambda notation and all the threads linked to it.Mahmoud
I have edited the q and voted to reopen it. I think it's clear now. But for an answer, you can see my answer herePatman
#506350Elijaheliminate
V
3

I think you confused about lambda expressions and anonymous methods. What you need to understand is that lambda expressions are just syntantic sugars.For example, you can create an anonymous method that takes 2 integer parameter and returns an integer like this:

Func<int, int, int> func = delegate(int x, int y)
                           {
                                return x + y;
                           };

Using lambda syntax you can shorten that statement into this:

Func<int, int, int> func2 = (x,y) => x + y;

Also you don't really need to pass any argument to a lambda statement.For example this is completely valid:

Action act = () => Console.WriteLine("hello world");

So as a result, lambda expressions allows you to create anonymous methods with less code and they don't have any disadvantages as compared to anonymous methods because they are completely different things.You are comparing apples with oranges.

Vesica answered 7/4, 2014 at 21:14 Comment(3)
But the old C# 2-style anonymous method can leave out all the parameters entirely, like for the zero "function" of two arguments, it could be Func<int, int, int> funcZero = delegate { return 0; };. With a lambda syntax you have to give both parameters (even if you don't use them), but their types can be inferred, so Func<int, int, int> funcZero = (x, y) => 0;.Mahmoud
@JeppeStigNielsen which is what OP is asking. You could have provided an answer!Patman
The answer is not an answer, but the comment is.Tripos

© 2022 - 2024 — McMap. All rights reserved.