When comparing anonymous methods to lambda expressions, I've seen explanations that anonymous methods provide flexibility.
Flexibility here means that you can omit parameters from anonymous methods.
// inflexible anonymous method
Action<int> action = delegate(int number)
{
Console.WriteLine($"Anonymous method: {number}");
}
action(1234);
// Output
// Anonymous method: 1234
// flexible anonymous method
Action<int> action = delegate
{
Console.WriteLine("Anonymous method");
}
action(1234);
// Output
// Anonymous method
Action<int> action = (number) =>
{
Console.WriteLine($"Lambda expression: {number}");
};
action(1234);
// Output
// Lambda expression: 1234
However, I have two questions.
First, how does an anonymous method with an omitted parameter use the passed value? (1234 here)
Second, where do you use the flexibility that anonymous methods provide?
I'll only answer the first question. The second question is highly opinion based, depends on context and at best I can offer incomplete / insufficient examples. Refer to the examples offered in Action Delegate. One use case is Composability
It doesn't. The generated IL (intermediate language) doesn't account in any way for the provided argument. Which seems logical because if it does, it needs to have knowledge about all the callers of that method.
On IL_001F the value 1234 is pushed on the stack. In <Main>b__0 there is no "pop" from the stack. So the value is lost.
If you would have a method that takes an
int, like sovoid test(int arg)the IL would look like:Here it does "pop" the argument of the stack in IL_005.
It is worth remembering that a delegate is a generated type that derives from System.Delegate and there is an implementation detail you see on line IL_0024.
Do note that your first and last example return the same IL for the .Net 6 compiler, which you can inspect here