# Thursday, December 11, 2008
« WF 4.0: Asynchrony and Persistence | Main | Running VS 2008 elevated has some downsi... »

I think the best feature introduced in .NET 2.0 was anonymous methods in C#. Hows that for taking a stance!

I've just been reading an article about anonymous methods coming to VB in .NET 4.0 and while I think this is great news for VB developers its worth adding a note of caution due to one of the examples used. Generally anonymous methods and event handlers can cause unforseen issues due to the way anonymous methods are implemented under the covers (I'm assuming the VB implementation is broadly the same as the C# one). If you look at the code below:

class Program
{
    static void Main(string[] args)
    {
        Foo f = new Foo();

        f.ItHappened += delegate
        {
            Console.WriteLine("Foo happens");
        };

        f.ItHappened -= delegate
        {
            Console.WriteLine("Foo happens");
        };

        f.Bar();
    }
}

class Foo
{
    public event Action ItHappened;

    public void Bar()
    {
        if (ItHappened != null)
            ItHappened();
    }
}

The problem is the compiler generates two different real methods for the two anonymous methods. Therefore the unwiring of the handler fails. It comes down to this: if you wire up an event hander with an anonymous method, unless you store the delegate in a variable, there is no way to remove that event handler afterwards. There is a well known issue in .NET in terms of memory leaks with event handlers keeping alive objects that otherwise have independent lifetimes. You fix this issue by remembering to remove the event handler when the object is finished with. However, using anonymous methods (or lambdas for that matter) prevents you from removing the event handler and so this issue becomes unresolvable.

So my advice: even though anonymous methods are very powerful, generally use real methods for event handlers unless the lifetime of the event owner and the subscriber are inherently tied together.