Jaa


using anonymous methods for adapter code

Sometime back I had blogged about whether programmers really use anonymous methods. Recently I found a problem for which anonymous method felt like a natural choice.

I am currently coding an UI glue layer. I need it because I have some stable back-end code (with event-handlers) which I have to tie with some new UI. The problem is that the event handler signatures of the backend matches some other UI technology that was used before (which I cannot modify). The signature doesn't match the one required by the UI technology I'm glueing it to. Interestingly these handlers were not added using += but using some methods which got the handler as a parameter.

The first solution that comes to mind is to change the method that adds the handler so that it creates an instance of some adapter class. The adapter class has [in] and [out] event handlers. The [in] handler matches the new UI-technology specific signature and the [out] matches the older signature. Objects of this class is created by the API and the [in] handler is tied to the UI-events and when it gets fired it simply calls the [out] handler.

The problem with this approach is defining all the adapter classes and coding them up. Anonymous methods with outter variable reference solves this problem elegantly.

 public override object AddFocusChangeEventHandler(MyEventHandler eventHandler){    UISpecificEventHandler uiHandler =         delegate(object sender, UISpecficEventArgs e)        {            // Convert sender and UISpecificEventArgs to what            // matches MyEventHandler and call it.            eventHandler(converterSender, convertedArgs);        };    UI.AddFocusChangedEventHandler(uiHandler );    return uiHandler;}

With this I'm easily done as C# automatically generates hidden classes to wrap the anonymous method when there is a reference to an outter variable (variable defined outside the anonymous method, eventHandler in this case).