This post originated from an RSS feed registered with Java Buzz
by Simon Brown.
Original Post: Having fun with C# delegates
Feed Title: Simon Brown's weblog
Feed URL: http://www.simongbrown.com/blog/feed.xml?flavor=rss20&category=java
Feed Description: My thoughts on Java, software development and technology.
Although I couldn't quite get my first example of C# delegates working, I've been having a lot of fun using them elsewhere. In this particular example, I've been using delegates to point to validation methods as a really simple way to conditionally invoke different blocks of validation code. However, the really nice part about all of this is that C# supports the chaining together of delegates, without the need to manually manage a list of objects yourself. Basically, once you have a delegate defined, you simply use the overloaded += operator. Here's an example.
// declare the delegate
delegate void ValidateDelegate();
ValidateDelegate validators;
// add some delegates
validators += validateSomething;
validators += validateSomethingElse;
// call all delegates in the chain
validators();
In Java, I would have implemented something similar by defining a simple interface and then perhaps implementing that interface using a bunch of anonymous inner classes. The nice thing about delegates is that you can do all of this in a much lighter and more dynamic way.