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.
We'll cover the following...
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.
Line 1: We instantiate the
printerdelegate using thedelegatekeyword 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
MessagePrinterdelegate type at the end of the file. ... ...