- Introduction
- Reviewing Delegates
- Anonymous Methods Are Inline Delegates
- What the Marketing Material Says
- Summary
What the Marketing Material Says
Are anonymous methods a good thing? The marketing material says that anonymous methods are good because they reduce code overhead caused by instantiating delegates and reducing separate methods. But the marketing material also says that anonymous methods increase usability and maintainability. I thought well-named methods did that. Does this code look easily maintainable?
private void Form1_Load(object sender, EventArgs e) { BindClick(delegate { Debug.WriteLine("button1 click"); }); } private void BindClick(EventHandler handler) { button1.Click += handler; }
In this sample, we're passing a delegate to a method by passing the delegate as an anonymous method. Just keeping the order and number of the parentheses, semicolons, and brackets straight is a pain in the neck.
The cited classic example is that anonymous methods can reduce the overhead of creating delegates and methods just for kicking off threads (which use delegates). This is true, but threads are used infrequently and are already difficult enough to use correctly; I wonder how prudent it is to make the code more esoteric rather than less.
Linguistically, I love methods, but as a practical matter anonymous methods may just be an example of some inventive person at Microsoft being a bit too clever.