views:

100

answers:

4

I want to know the sequence of how these function are called. Like if our heap is full, GC will be called. It will mark the object and call its finalise operation, now we have sweep stage.. in which the reference to that object is deleted and object becomes inaccessible.. So where does the destruction come in cycle...When wld it be called..What wld it be doing then....

+2  A: 

There is no "destructor" in C#/.NET, although the term seems to have been used interchangeably with "finalizer" in the past.

Most of the time, you shouldn't be implementing finalizers either; the main instance where you need to use those is if the class holds on to unmanaged resources, in which case you should be implementing the IDisposable pattern (technically, you could call Dispose a "destructor", but it does not actually free any memory on the heap, which is an important distinction when discussing memory management).

Don't second-guess the GC in terms of memory management. Just make sure you release any unmanaged resources you use (file handles, etc.). And if you see someone using the term destructor, they probably meant to say finalizer.

Aaronaught
+2  A: 

I have to recommend the source on this one. Eric Lippert from the C# compiler team made a recent post on this exact subject: What’s the difference between a destructor and a finalizer?

From their accepted definitions, they're actually backwards in C#. Read his post though, I can't describe it any better.

Nick Craver
+1 for the link, I had a vague recollection of Eric posting about that but couldn't remember when/where. Just keep in mind that what's referred to as a "destructor" in that post does not actually free any memory, so it's not the same as a destructor in C++.
Aaronaught
@Aaronaught: Correct. A destructor frees a *resource*. The garbage collector *manages memory*.
Eric Lippert
+2  A: 

There are many, many documents which explain how the .NET garbage collector works. Here are a few to start with:

http://msdn.microsoft.com/en-us/magazine/bb985010.aspx

http://msdn.microsoft.com/en-us/library/ms973837.aspx

http://www.simple-talk.com/dotnet/.net-framework/understanding-garbage-collection-in-.net/

Eric Lippert
+1  A: 

A Very good video about .Net Memory management is at .Net Memory Management. It will help clear your doubts about finalizer and when it is called, how it is called, etc.

Darshan
Very informative video!!
Antoops