Reputation: 15958
This line of code allocates a space of memory on the heap to the object foo
var foo =new object();
Will this line of code free it up?
foo=null;
Or is it just wiping out the reference to a memory location on the heap.
Upvotes: 1
Views: 220
Reputation: 10171
In C#, all objects are garbage collected, you can't "delete" them.
When the last reference to a given object falls out of scope, the object is liable to collection. You can certainly null as many references as you can find, but the object will remain alive as long as any reference still holds that object.
So setting foo=null;
it just remove reference.
Garbage collection consists of the following steps:
- The garbage collector searches for managed objects that are referenced in managed code.
- The garbage collector tries to finalize objects that are not referenced.
- The garbage collector frees objects that are not referenced and reclaims their memory.
It's important to understand how garbage collectors work GC Class
// Set a break-point here to see that foo = null.
// However, the compiler considers it "unassigned."
// and generates a compiler error if you try to
// use the variable.
object foo;
// Now foo has a value.
foo = new object();
// Set foo to null again. The object it referenced
// is no longer accessible and can now be garbage-collected.
foo = null;
Upvotes: 2
Reputation: 850
It just removes the reference. The object itself is garbage collected when the runtime sees fit, and is actually independent of whether or not the reference is erased.
Upvotes: 3