Peace For All

March 13, 2013

C# Feature Need: Lambdas having an implicit reference to themselves

Filed under: C#, Programming — Tags: , , , — Devlin Bentley @ 1:07 pm

I really want a “me” keyword in C# that gives a reference to the current lambda.

For event handling it is often useful to have a one time event that detaches itself after it has fired. Currently this isn’t too hard, you assign said event to a nice Func<T…> or Action<T…> (or actual event handler delegate type) and when you reference it in your lambda (while unassigning it) it gets captured in your closure.

An example of this is:

EventHandlerType handler = null;
handler = (string receivedString) =>
    {
        this._someString = receivedString;
        EventClass.Event -= handler;
    };
EventClass.Event += handler;

As you can see above, handler is my event handler, it takes in a lone string (because event args is for chumps), assigns said string to a class member variable, and then detaches itself.

This isn’t horrible, but it still is a fair pain in the arse. I’d presuming the lambda already has a reference to itself somewhere, so my creating an explicit one seems sort of redundant. Also it is an unneeded closure, quite frequently that is the only variable I am closing over, which means I have a fairly sizable overhead just to capture a reference to myself!

On a separate note, I wonder if declaring your handlers as class members optimizes this in any way. I am not 100% sure if they are captured over, I should read up on it to see if I can find clarification. Thinking about it some more, there may be times when there is a need to capture them, but if they are public members this might not be needed. I am now wondering if the C# compiler is smart enough to optimize this away.

Anyway, none of that would matter if C# had a keyword that said “give me a reference to the bloody function I am in right now!”

And hey, type inference means the syntax could be really nice! 🙂

(And if there is already a way to do this, that doesn’t involve gobs of reflection code, please do tell!)

Now this really becomes a pain when you are trying to chain event handlers together. I have some annoying lock step code I need to write where I do a call-handle-call-handle over a network channel. Each message I get is of the same type (so it flows through the same event), but the handler has to be different each time.

Now obviously I could make one giant lambda that tracks its state and how many times it has responded to messages, but I much prefer simpler lambdas that do exactly one thing. Thus I am constantly unassigning and reassigning handlers to the same event. My code would be a lot cleaner if I didn’t have to predeclare all my handlers.

(Of course this code is dealing with an impedance mismatch between an non-OO system and my OO system, so the code is going to be somewhat ugly, but I prefer to minimize this as much as possible!)

Advertisements

Blog at WordPress.com.