Reputation: 4513
I've got 2 list
s, where both hold objects of same type. Let's call it TypeX
.
When I want to add a new object of TypeX
I'd create a new object of TypeX
and then use Add
to list1
and to list2
. Thus each list will have a reference to the actual object.
(I hope I'm right here).
Then, I'd want to remove the object. I'd use Remove
for both list
s. Thus the reference to the object has been removed...
But what happens to the object itself? Will the GC clean it? Should I remove it somehow else?
Upvotes: 0
Views: 104
Reputation: 12372
The good thing about having a GC is that you really don't need to worry about what your're worrying now.
Upvotes: 0
Reputation: 4028
If there's no more references to the object, the GC will collect the object when it finds necessary. This usually happens when the memory pressure increases or by manually giving it a 'hint' to run (you usually don't need this).
This link may be helpful: http://msdn.microsoft.com/en-us/library/ms973837.aspx
Upvotes: 0
Reputation: 70369
As long as the only references to the object are in those lists the GC will remove it after you removed it from both lists.
Upvotes: 0
Reputation: 174299
In simple terms, the GC collects every object that is not referenced by any other object.
So, if you remove your object from both lists and don't save it anywhere else it will eventually be garbage collected.
Upvotes: 3
Reputation: 22016
The short answer is yes, the GC will clean it up. However if you wish to make this more efficient I would add the interface IDisposable to your object so that the GC will dispose of the object cleanly as soon as all reference to it has gone.
http://msdn.microsoft.com/en-us/library/system.idisposable.aspx
Upvotes: 0