If a base class publishes a C# event and a derived class subscribes to it -- i.e. subscribes to itself --. Will the event subscription prevent the object from being garbage collected? Or is the garbage collector smart enough to detect such circular reference situations.
At first glance, it seems like it should but I'm pretty sure I've seen control code that does this. This is such a fundamental question I can't believe I've never looked into it before.
Edit: For Juan R. I mean something like this. (Never compiled this code, just typed it off the top of my head so I might have typos/errors)
public class Base
{
public event EventHandler<double> ValueChanged;
}
public class Derived : Base
{
public Derived()
{
// Will this prevent my object from being collected?
ValueChanged += OnValueChanged;
}
private void OnValueChanged(object sender, double v)
{
}
}
An object subscribing to its own event will not cause a memory leak for the simple reason that the CLR GC is based on reachability, not reference counting. If the object is reachable from a GC root, then it was not eligible for GC anyway. And if it's not reachable, then a self-reference does not make it reachable. There is nothing special about events with regard to GCing circular references.