Delegate mystery RRS feed

  • Question

  • Hi,

    I have for some reasons the following code in my application:

    public static void SetDefinitions(DependencyObject d, ObservableCollection<Definition> value)
    d.SetValue(DefinitionsProperty, value);

    value.CollectionChanged +=
    delegate(object sender, NotifyCollectionChangedEventArgs e) { Update(d); };


    Now, my question is, how is the code actually compiled?
    If the instance of "d" will be in future released, won't the delegate cause a memory leak?
    Because the delegate is created within a static method, it must hold a reference to "d" instance; will that be properly released by GC, too?

    Thanks a lot,

    Wednesday, November 19, 2008 12:03 PM


  • The C# compiler generates a small helper class to implement the anonymous method.  The "d" reference will be a member of that class.   An active reference to "d" will thus exist through the reference to the helper class object held by the CollectionChanged member, preventing it from getting garbage collected until you remove the event handler.  Which you can't do.  Or the "value" object gets collected, which collects the CollectionChange member, which collects the helper class object which collects "d".  The circular reference, "d" referencing "value", is not a problem.

    Long story short, the lifetime of "d" is controlled by "value".  Which I think is exactly what you need.

    Hans Passant.
    • Marked as answer by Tomas Bouda Wednesday, November 19, 2008 12:40 PM
    Wednesday, November 19, 2008 12:19 PM