We have no control over when the destructor is called, because the times it is called are determined by the garbage collector. In a general sense the garbage collector reads for items that are not being currently used by the application. When it considers an item is ready to be destroyed, it calls the destructor (if there is one) and takes back the memory that was borrowed to store the item. Destructors are also called when the application exits. Any destructor implicitly calls the Finalize method of the base class.

// So basically this:
class MyClass
{
    ~MyCass()  // destructor
    {
        // cleanup statements
    }
}

// Is eventually just implicitly converted to:
protected override void Finalize()
{
    try
    {
        // Cleanup statements
    }
    finally
    {
        base.Finalize();
    }
}

You should really be more specific with your questions though.

Jamie

Comments
you put C# instead of C ,do you know C don`t have class and object

If you are using C# this is a very good response. If you are using plain C, then the process of returning used memory to the system is completely authomatic and you don't have much control over it.

hey Dude
You must know 2 things

  1. C language does not depend on OOP it based on Structured programming
  2. C language does not have Destractor because it did not have any class (i.e Not oop lang)

You can try in C# language to perform destractor like this

class MyClass
{
~MyCass() // destructor
{
// cleanup statements
}
}

Edited 3 Years Ago by Dani: Formatting fixed

This guy posted a spam post obviously because it's his only post, and he hasn't been online since he posted; also his account was created the same day the post was made. Granted that's how I started my account because I was leery of whether or not the site would help, but when I came back to check my post it was helpful and I decided to stay around. However I already answered the thread perfectly. We all know there are no destructors in C because it's not object oriented; so I posted a C# destructor example because it was obviously a type-o.

Jamie

This article has been dead for over six months. Start a new discussion instead.