Women in Technology

Hear us Roar

  A Java Programmer Looks at C# Delegates
Subject:   anonymous inner classes
Date:   2003-05-22 11:30:52
From:   anonymous2
Response to: anonymous inner classes

Snonymous inner classes in Java play two roles, one is standing in for a reference to a method, to which delegates do represent an improvement, at least in terms of avoiding syntatic clutter.

The second semantic feature they provide is that of a closure (albeit with a few limitations), or in other words, a block of code which captures state from its lexical context. In this role they are very useful, although the wordiness of the construct in Java leads me to use them less than I would in languages with more spartan closure-like constructs.

So delegates should not be seen as a complete replacement for anonymous inner classes, but a specialization that helps reduce syntactical clutter for that specific use.

And you are correct that in our solution, attempting to create a delegate on a method that does not provide the correct type signature will not be discovered till runtime. I'm not sure how you would avoid that problem short of extending the compiler itself.

Full Threads Oldest First

Showing messages 1 through 1 of 1.

  • anonymous inner classes
    2003-05-23 12:08:36  anonymous2 [View]

    Delegates actually are bound to a class (although delegates referencing static methods are also possible).
    For example, you could have "delegate int CountDelegate()" and then have "new CountDelegate(CounterInstance.CountMethod)". In that case the CounterInstance holds the counter state between delegates calls. This is similar to what an inner class would achieve.

    I detail this some more in an article (http://blog.monstuff.com/archives/000037.html) that shows that the delegate holds both an object (state) and a method pointer, and also goes through the implementation details.