views:

158

answers:

2

I know a lot of the uses of .Net delegates can be emulated in Java by using a combination of interfaces and anonymous classes, but are there any situations where delegates have a real advantage and there is no Java equivalent?

+8  A: 
  • Much more concise syntax in C# with lambda expressions and anonymous methods
  • Type inference
  • General support for delegates in the language (method group conversions etc)
  • Multi-cast delegates with language support
  • Events (simple syntax for the observer pattern based on delegates)
  • Asynchronous execution via the system thread-pool
  • Expression trees with language support

Yes, a lot of it can be done in Java, but it's just painful.

Imagine writing LINQ queries but without lambda expressions, extension methods etc. It would be hideous. The same goes for a lot of other places where delegates are the natural solution in C# or .NET - the idiomatic Java solution often doesn't use anonymous inner classes because they're so darned ugly.

Jon Skeet
A: 

real closures with anonymous methods in c#

with anonymous classes in java, you have to declare every variable, you use from the outer scope, as final