9

Hello,

I have been trying to learn c# from dotnet tutorial and they gave this code which supposed to trigger garbage collector and in turn call the Destructor of the class. however when I run the same code, I get result of Constructor only and not the Destructor.

using System;
namespace DestructorExample
{
    class DestructorDemo
    {
        public DestructorDemo()
        {
            Console.WriteLine("Constructor Object Created");
        }
        ~DestructorDemo()
        {
            string type = GetType().Name;
            Console.WriteLine($"Object {type} is Destroyed");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            DestructorDemo obj1 = new DestructorDemo();
            DestructorDemo obj2 = new DestructorDemo();

            //Making obj1 for Garbage Collection
            obj1 = null;
            GC.Collect();
            Console.ReadKey();
        }
    }
}

here is the code, if you know please tell me why it's not working

you are viewing a single comment's thread
view the rest of the comments
[-] copygirl@lemmy.blahaj.zone 5 points 5 days ago* (last edited 5 days ago)

My recommendations would be:

  • Do not rely on GC.Collect() in any real program code. Just let the GC do its thing.
  • If you need guarantees about when the destructor (or equivalent) is called, use the dispose pattern and use a using statement or declaration explicitly so Dispose gets called as soon as possible.
class DestructorDemo : IDisposable
{
    public string Name { get; set; }
    public DestructorDemo(string name)
    {
        Name = name;
        Console.WriteLine($"demo object {Name} constructed");
    }
    public void Dispose()
    {
        Console.WriteLine($"demo object {Name} disposed");
    }
}

using var obj1 = new DestructorDemo("obj1");

using (var obj2 = new DestructorDemo("obj2"))
{
    Console.WriteLine("Press key to dispose 'obj2'");
    Console.ReadKey();
    // obj2 goes out of scope at the end of the block
    // this will automatically call `.Dispose()` on it
}

Console.WriteLine("Press key to dispose 'obj1' and exit");
Console.ReadKey();

// obj1 goes out of scope here

Note that this code is just to showcase the using keyword (in relation to IDisposable). If you want to implement the disposable pattern properly you should look at the help article I linked. Such as making sure that Dispose is called even if the object is naturally garbage collected, that is if you forget to use using. (I also didn't check the validity of the code but it should get the idea across.)

Unless the purpose is to get a destructor to trigger only. This is the most correct answer. This pattern is very widely used and can prevent crashes. The using block is a try{}finally{} behind the scenes but without the catch it just throws and could be caught higher up the stack on accident. When I was a fresh grad this pattern saved my dumb ass when I unintentionally would catch the exceptions somewhere else, but hey it didn't crash.

this post was submitted on 16 Dec 2025
9 points (100.0% liked)

C Sharp

1749 readers
2 users here now

A community about the C# programming language

Getting started

Useful resources

IDEs and code editors

Tools

Rules

Related communities

founded 2 years ago
MODERATORS