Search⌘ K
AI Features

Anonymous Methods

Explore how to create and use anonymous methods in C# within the context of delegates and events. Understand syntax, passing anonymous methods as parameters, omitting parameters, returning values, and accessing outer variables through closures to write concise and flexible code.

Anonymous methods are inline methods defined without a name. We use them to instantiate delegates directly instead of declaring a separate named method. The syntax for creating an anonymous method is as follows:

delegate(parameters)
{
// Method body
}

Let’s see how we apply this syntax in practice.

In this example, we create a delegate instance using an inline anonymous method.

C# 14.0
MessagePrinter printer = delegate()
{
Console.WriteLine("Hello World!");
};
printer();
// Delegate definition
delegate void MessagePrinter();
  • Line 1: We instantiate the printer delegate using the delegate keyword followed by ().

  • Lines 2–4: We define the body of the anonymous method directly inline.

  • Line 6: We invoke the delegate, which executes the anonymous method.

  • Line 9: We define the MessagePrinter delegate type at the end of the file. ... ...