Reputation: 57
I just don't know that where the variable used in some method has gone after the method's execution completed, please see the code snippet below:
void Foo()
{
List<object> conditionedObjList;
conditionedObjList = GetConditionedObjectList
(
new List<object>() { /*there are many unconditioned objects here*/}
);
}
My question; is the variable myObjList
defined in method GetConditionedObjectList
will be disposed after myObjList
has returned or we need to dispose it manually?
private List<object> GetConditionedObjectList(List<object> originalObjList)
{
List<object> myObjList = new List<object>();
/*do some selection*/
myObjList.AddRange(new object[]{/*there are 100 conditioned objects here*/});
return myObjList;
}
Upvotes: 2
Views: 1785
Reputation: 98766
C# has garbage collection. Objects are created on the heap, and are only collected when the object has no more references to it.
myObjList
just stores a reference to the actual object which is on the heap; when you return this reference and store it in a variable, you're guaranteeing that the garbage collector (GC) won't pick it up.
If by "disposed" you mean "destroyed" or "removed from memory", then the garbage collector does this for you; all you need to do is remove references to the object. For example, you could set conditionedObjList
to null
after calling the function. Then the GC would be free to pick the unreferenced object up. Note that this isn't immediate; the GC only runs periodically in order to be more efficient.
Upvotes: 1
Reputation: 254926
IDisposable
- so we don't need to dispose it at all.Upvotes: 1
Reputation: 11263
It is not disposed as you are returning a reference to it.
It would have gone out of scope if it was only used in function locally in that case after function returns there are no references to it, therefore GC is free to collect it.
BTW List<T>
doesn't implement IDisposable therefore it doesnt need to be disposed in your code.
Upvotes: 1