- Introduction
- Reviewing Delegates
- Anonymous Methods Are Inline Delegates
- What the Marketing Material Says
- Summary
Anonymous Methods Are Inline Delegates
Generally, when we're using delegates, we have a method. That method's signature matches the signature prescribed by a delegate and can be used to initialize a delegate instance. Anonymous methods are used to condense the method and initialization of the delegate into a single location.
Using the example from the previous section, we see how the instantiation of the delegate new EventHandler is distinct from the method OnClick used to initialize the delegate. This code could be compressed into an anonymous method:
private void Form1_Load(object sender, EventArgs e) { button1.Click += delegate { Debug.WriteLine("button1 clicked"); }; }
To create the anonymous method, notice that we removed OnClick's method header and replaced the construction of the EventHandler delegate with the word delegate followed by OnClick's method body. The resultant behavior is the same. If we want to use the event arguments we would normally find associated with the delegate, we can add an optional parameter list after the word delegate:
private void Form1_Load(object sender, EventArgs e) { button1.Click += delegate(object s, EventArgs ev) { Debug.WriteLine("object is " + s.ToString()); }; }
If you define delegate parameters, they must match the parameters defined by the delegate type. For example, Click's type is EventHandler, so if arguments are present they must match EventHandler's arguments object and EventArgs.
Anonymous methods can be used wherever delegates are expected. Anonymous methods can use ref and out arguments, but cannot reference ref or out parameters of an outer scope. Anonymous methods can't use unsafe code, and anonymous methods can't use goto, break, or continue in such a way that the branch behavior causes a branch outside of the anonymous method's code block.