0
Employee obj = new Employee();

obj.Dispose(); //statement 1;
obj = null; //statement 2

On which statement will the GC remove the object?

Exactly what will be happening behind the scene on statement 1 and statement2

manish
  • 21
  • 6

1 Answers1

1

It could be any of those, or none.

If the default constructor and the Dispose method have no side-effects and the compiler can see that, it could skip code generation for your snippet altogether, by considering the whole thing a no-op.

Alternatively, if only the Dispose method is a no-op, then the GC could collect the object just after this line:

Employee obj = new Employee();

Alternatively, if the GC can prove that the object is never read again after Dispose (even if it's still in scope), it could collect the object just after this line:

obj.Dispose();

Alternatively, if the GC can't prove any of these, it could do it any time after this line:

obj = null;

Alternatively, if the GC doesn't see any pressure to recycle memory, it might not collect the object at all during the entire execution of the program.

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104