Jose
Jose

Reputation: 11091

Does this cause a memory leak (in .NET)?

I have a memory leak question. Will the instances of obj ever be eligible for garbage collection until the class instance of TopClass goes out of scope?

public class TopClass
{
  public void MyFunction()
  {
    TestClass obj = new TestClass();
    obj.PropertyChanged += (s,e) => { //Do some code };
    obj = null;
  }
}

Furthermore that would make all objects that instantiate a TopClass and invoke MyFunction() to not be eligible for GC right?

I understand that in managed code once the application goes out of scope then all the objects are eligible, but I want to know WHILE my app is running this will cause a memory leak. Right?

Upvotes: 2

Views: 163

Answers (2)

zneak
zneak

Reputation: 138041

Nope. obj will be collected all right. Nothing in this code causes a strong reference.

An object can be kept alive by being attached as an event handler, but an object cannot be kept alive by having event handlers.

Upvotes: 4

Thomas Levesque
Thomas Levesque

Reputation: 292405

obj will be eligible to garbage collection as soon as you set it too null (but the actual collection will be done later of course). Subscribing to the PropertyChanged event doesn't create a reference to obj, it creates a reference from obj to the instance of TopClass. And it won't prevent collection of the TopClass instance either, unless it's referenced somewhere else

Upvotes: 3

Related Questions