3

I have a class which has a static List<T> field inside which I hold all my objects; each object represents a process that is running and its properties.

After the process finishes its job, the relevant object is removed from the List<T>, then my UI is updated.

After the object is removed from my list, should I change this object to null to free resources?

Niall C.
  • 10,878
  • 7
  • 69
  • 61
user2813889
  • 71
  • 1
  • 9
  • 2
    What you should definitely do is add code to go with the description. But to answer the question: if the object reference is going to go out of scope anyway there's no reason to set it to `null`. – Jon Oct 04 '13 at 18:14
  • 1
    It kind of depends on what you mean by "change this object to null". That could be interpreted a number of ways that are very different from each other. – hatchet - done with SOverflow Oct 04 '13 at 18:20

4 Answers4

10

Once you remove the object from the list, the object still exists but if no reference is being made to that object, the garbage collector will clean it up and you won't have to worry

Alan
  • 171
  • 3
  • 1
    And what about unsubscribe to this object event ? its also handle by garbage collector due to there is no reference is being made ? – user2813889 Oct 04 '13 at 18:17
  • @user2813889 subscribing to events of Broadcaster doesn't prevent garbage collection of the Broadcaster..If Broadcaster goes out of scope,it will be collected by gc – Anirudha Oct 04 '13 at 18:22
8

C# is garbage collected so either way the memory will be taken care of.

ford prefect
  • 7,096
  • 11
  • 56
  • 83
5

The moment you remove that object from list,the object would go out of scope and it would be eligible for GC..


In terms of Events:

Even if that object has some events to which other objects subscribe,it would still be elgible for GC..

So, its a one way relation

Broadcaster -> Subscribers

If Broadcaster goes out of scope it would be eligible for GC even if it has subscribers..

But Broadcaster would prevent GC of Subscribers

Have a look at Do event handlers stop garbage collection from occuring?

Community
  • 1
  • 1
Anirudha
  • 32,393
  • 7
  • 68
  • 89
3

In short, no.

Once a reference falls out-of-scope, the Garbage Collector will get rid of the object/references to it. This can also be handled with the using (if the object implements IDisposable) keyword as well. Basically, don't set it to null and let the clean-up mechanisms within C# handle the work for you.

Brian
  • 5,069
  • 7
  • 37
  • 47
  • 2
    `This can also be handled with the using keyword as well.`, only if the object implements `IDisposable`, if It does, then one has to manually call `Dispose`, `using` statement might not be used since the object is staying in the list. – Habib Oct 04 '13 at 18:20