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;
}
C# has garbage collection. Objects are created on the heap, and are only collected when the object has no more references to it.
myObjListjust 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
conditionedObjListtonullafter 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.