Garbage Collection on objects not assigned to a variable

266 Views Asked by At

I am working on project that uses this pattern

var businessEntity = new DAL().GetObject(id);
// do something with the business entity.

Has anyone followed this pattern?

Does this cause any memory management issues? Any complications with the garbage collector?

Thanks

4

There are 4 best solutions below

1
On BEST ANSWER

It works just fine. It will be garbaged collected just fine. Depending on the implementation and the object, either at the end of the line it will be marked for collection, or once businessEntity goes out of scope.

0
On

No, the GC eventually will clear the DAL object if nothing else needs to be done with it or nothing else is pointing to it. You have a reference to the businessEntity object, so the GC won't touch it until the reference is invalidated.

3
On

This object will be live while its referenced by businessEntry and will be collected sometime after the variable goes out of scope

0
On

It is very typical code and no, it doesn't cause any problems with the garbage collector.

A reference to the unnamed object is in the VM stack (otherwise the method could not be called), which is in the root set of the GC.