In C#, an anonymous method is a method without a name that is defined using the delegate keyword. Instead of declaring a separate named method, anonymous methods allow developers to inline the implementation directly at the point of use.
They are mainly used with delegates and event handling to make code concise and localized.
Syntax
delegate(parameters){
// Code block
};
Key Points
- Introduced in C# 2.0 as a shorthand for delegate implementation.
- Created using the delegate keyword without specifying a name.
- Useful for event handlers and one-time delegate assignments.
- Can access outer variables (closure) from the scope where they are defined.
- Later evolved into lambda expressions (introduced in C# 3.0).
Example 1: Basic Anonymous Method
OutputMessage: Hello from Anonymous Method
Explanation:
- A delegate ShowMessage is declared.
- Instead of creating a separate method, the implementation is written inline using delegate.
- The message is passed and executed immediately.
Example 2: Anonymous Method with Event Handling