1

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

Kara
  • 6,115
  • 16
  • 50
  • 57
Nick Harrison
  • 921
  • 9
  • 17

4 Answers4

2

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.

EnabrenTane
  • 7,428
  • 2
  • 26
  • 44
  • `businessEntity` may not hold a reference to the unnamed object `DAS`, so this is not true. The concept of "out of scope" with garbage collectors is also misleading and potentially wrong, see for example http://blogs.msdn.com/b/oldnewthing/archive/2010/08/10/10048150.aspx – Giuseppe Ottaviano Jan 12 '11 at 09:32
1

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.

Giuseppe Ottaviano
  • 4,533
  • 2
  • 18
  • 18
0

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
-1

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

Andrey
  • 20,487
  • 26
  • 108
  • 176
  • 1
    That's not true; 'businessEntry' may is not a reference to the intermediate object, it is a reference to whatever GetObject returned. – Ed S. Jan 12 '11 at 01:49
  • @Ed: That was the object in question and that's what I said - I didn't mean (new Dal()) object in any way. Please remove your minus. – Andrey Jan 12 '11 at 02:49
  • I won't, because that is obviously not what you said. *This object will be live while its referenced by businessEntry and will be collected sometime after the variable goes out of scope* - The OP asked about the object created by the expression new DAL(), so your answer is misleading/wrong. – Ed S. Jan 13 '11 at 08:37