Recall that an instance of a delegate is an object that refers to one or more methods. Code that has access to the delegate instance can execute the various methods via the delegate.
1
2
3
4
5
6
7
8
9
10
11
12
| private delegate void StringHandlerDelegate( string s); static void Main() { StringHandlerDelegate del1 = Method1; del1( "Invoked via delegate" ); } static void Method1( string text) { Console.WriteLine(text); } |
An anonymous method is a shorthand for declaring a delegate instance that allows declaring the code to execute as part of the delegate’s declaration, rather than in a separate method.
The code below is equivalent to the example above, but using an anonymous method, rather than a separately defined method.
1
2
3
4
5
6
7
8
| private delegate void StringHandlerDelegate( string s); static void Main() { StringHandlerDelegate del1 = delegate ( string s) { Console.WriteLine(s); }; del1( "Invoked via delegate" ); } |