Nick Harrison
Nick Harrison

Reputation: 937

Garbage Collection on objects not assigned to a variable

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

Upvotes: 1

Views: 266

Answers (4)

EnabrenTane
EnabrenTane

Reputation: 7466

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.

Upvotes: 2

Giuseppe Ottaviano
Giuseppe Ottaviano

Reputation: 4633

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.

Upvotes: 1

Andrey
Andrey

Reputation: 21285

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

Upvotes: -1

BoltClock
BoltClock

Reputation: 723538

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.

Upvotes: 0

Related Questions