Category Archives: C#

Self-Referencing in Event Listener Delegates (C#)

This is perhaps a question of semantics, but perhaps not, so I ask: Is there an appreciable difference in the following 2 snippets?

public Parent()
{
    Child newChild = new Child();
    newChild.RequestSpecialEvent +=
        (sender, e) =>
        {
            newChild.DoMagic();
        }
}

or

public Parent()
{
    Child newChild = new Child();
    newChild.RequestSpecialEvent +=
        (sender, e) =>
        {
            ((Child)sender).DoMagic();
        }
}

Obvious difference is option 1 sort of self-references itself, while option 2 performs a cast on an object. Performance wise, I expect the cast is more expensive.

However, I’m theorizing that in option 1, it is technically the “Parent” which holds a reference to “newChild” (through the delegate defined within Parent), so even if newChild goes away (newChild = null or something similar), the newChild object can’t be garbage collected (gc’ed) because Parent has defined a delegate which is still attached to it. newChild can only be gc’ed when Parent eventually goes away.

However, in option 2, Parent never creates such a “hard reference” to newChild, so when newChild = null happens, it truly can be gc’ed immediately.

I prefer option 1 for its succinctness and readability, but worry that option 2 would be better. Thoughts? Is my theory correct or off-base? Is there an alternative or more preferred approach (with sound reasoning) for declaring the same event listener relationship with parent/child classes?