Skip to content

Anonymous Methods

Mario edited this page Sep 6, 2024 · 2 revisions
someDelegateOrEvent += delegate {
  Console.WriteLine("Anonymous method which ignores arguments.");
}

someDelegateOrEvent += delegate(int a, string b) {
  Console.WriteLine("Anonymous method which accepts arguments.");
}
  • Cannot access ref or out parameters in the outer method.
  • Cannot have local variables that are the same as in the outer method.
  • Stuff in the outer class scope works as expected.

Lambda Expressions

Various forms of lambda expressions.

() => Console.WriteLine("Hello.");

i => (i % 2) == 0

(i) => (i % 2) == 0

(int i) => (i % 2) == 0

(a, b) => a + b

(a) => {
  Console.WriteLine(a);
  return a + 1;
}

As of .NET 4.6, you can use lambdas for member methods too ("Expression bodied members").

class MyClass
{
  public int Add(int x, int y) => x + y;
}
Clone this wiki locally