Restart
Restart

Reputation: 57

Is this variable disposed after use?

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

Answers (3)

Cameron
Cameron

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

zerkms
zerkms

Reputation: 254926

  1. The List doesn't implement IDisposable - so we don't need to dispose it at all.
  2. It will be marked to be garbage collected as soon as you not have any reference to it.

Upvotes: 1

Sanjeevakumar Hiremath
Sanjeevakumar Hiremath

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

Related Questions