Hello friends, I never ever use a class destructor, and now I want to try to using destructor, but I have a small problem.

My code is:

using System;
using System.Text;

namespace ConstTest
{
    class test
    {
        public test()
        {
            Console.WriteLine("Start...");
        }

        ~test()
        {
            Console.WriteLine("End...");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            test t = new test();
            Console.Read();
        }
    }
}

And now, when I run the application then only displays "Start...", the destructor is not works. :/

Could someone give me an explanation about the problem ?
Thanks.

The whole idea of destructor is to release the resources your class instance has allocated during its lifetime and do other "cleanup" work.

For example

private byte[] _Big;

public test()
{
  // Allocate memory
  _Big = new byte[60000];
}

~test()
{
  // Release
  _Big = null;
}

In fact C# (.NET Framework) has a built-in garbage collector which handles things like memory de-allocation for you. There are only few occasions when you need explicitly write a destructor for your class.

One thing you definitely can't do in the destructor is to use Console.WriteLine(), popup a messagebox or similar since your object is actually "gone" in that point, and there's just cleanup work for GC.

Since you can't directly execute code in destructor, all you can do is to monitor your applications resource allocation (usually memory consumption) with some external resource monitor application (there are a few of them). For example, with the class above, you could check from a resource monitor what's the amount of allocated memory once you start your application. Then call a loop which creates a few thousands of instances from the class above, and re-check the allocated memory. Then destroy class instances by setting them null, and watch from the resource monitor how the amount of allocated memory decreases.

HTH

Teme64, thank you for the explanation. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.