Yes, delegates are very similar to single-method interfaces. However:
- CLR has built-in support for them
- Support within their framework, including multi-sheet capabilities and asynchronous calling
- Support for additional C # / VB languages ββin the form of method group transformations, lambda expressions, anonymous methods
- They have a mandate for events (i.e. events and delegates are a kind of matching pair)
- They mean that you do not need to implement the interface in a separate class for each delegate instance that you want to create.
The last point is the most important - consider the LINQ expression:
var query = collection.Where(x => x > 5) .Select(x => x * x);
Now imagine that if you express the logic x > 5 and x * x , you had to write a separate class for each expression and implement the interface: the amount of torsional and useful code would be ridiculous. Now, of course, the language could be designed to allow conversions from lambda expressions to implement the interface through separate classes, but then you still lose the advantage of being able to just write a separate method and create a delegate with that as a target. You would also lose reusable abilities.
As with a similar thought, consider looping statements like while and for . Do we really need them when we have goto ? Nope. But life is much better with them. The same can be said about delegates, as well as properties, events, etc. All of them simplify the development process.
Jon Skeet Jan 01 '11 at 19:22 2012-01-01 19:22
source share