Share via


Why is the destructor not making his job?

Question

Wednesday, January 23, 2019 8:24 PM

Hi All,

I have written the very basic program below, I am new to C#. The destructor ~Program() doesn't get called, so I do not see in the output the 'Destructor called' string. I have checked other similar questions but I don't find the answer to mine. Thanks.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static System.Console;

namespace LyfeCicleObject
{
    class Program
    {
        public Program()
        {
            WriteLine("Cons called");
        }

        ~Program()
        {
            WriteLine("Destructor called");           
        }

        static void Main(string[] args)
        {
            WriteLine("Main started");

            Program p1 = new Program();
            {
                WriteLine("Block started");
                Program p2 = new Program();
                WriteLine("Block ended");
            }

            WriteLine("Main ended");
        }

        }

All replies (10)

Wednesday, January 23, 2019 10:08 PM

Greetinhs Manuel.

The destructor will not be called until p1 and p2 go out of scope. Because they are declared in the Main method, this will not happen until the program has ended, so you will not have a chance to see "Destructor called".

Try the following code instead. In this code, p1 and p2 will go out of scope when DoStuff ends. This happens just before the program finishes (while Main is still running), so you should see the destructor string.

   class Program
   {
      public Program()
      {
         WriteLine("Cons called");
      }

      ~Program()
      {
         WriteLine("Destructor called");
      }

      static void Main(string[] args)
      {
         WriteLine("Main started");

         DoStuff();
      }

      static void DoStuff()
      {
         Program p1 = new Program();
         {
            WriteLine("Block started");
            Program p2 = new Program();
            WriteLine("Block ended");
         }
      }

   }

Thursday, January 24, 2019 3:18 AM

Hi All,

I have written the very basic program below, I am new to C#. The destructor ~Program() doesn't get called, so I do not see in the output the 'Destructor called' string. I have checked other similar questions but I don't find the answer to mine. Thanks.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static System.Console;

namespace LyfeCicleObject
{
    class Program
    {
        public Program()
        {
            WriteLine("Cons called");
        }

        ~Program()
        {
            WriteLine("Destructor called");           
        }

        static void Main(string[] args)
        {
            WriteLine("Main started");

            Program p1 = new Program();
            {
                WriteLine("Block started");
                Program p2 = new Program();
                WriteLine("Block ended");
            }

            WriteLine("Main ended");
        }

        }

The destructor/finalizer is doing its job: after the console window is dismissed, and before the application finishes.


Thursday, January 24, 2019 9:03 AM

Hi manuelalonge,

Thank you for posting here.

For your question, you could refer to the links below.

https://www.c-sharpcorner.com/UploadFile/72d20e/concept-of-destructor-in-C-Sharp/

https://www.dotnetperls.com/destructor

Best Regards,

Wendy

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Thursday, January 24, 2019 1:22 PM

Hi,

you want the destructor to be invoked if you leave the scope? Maybe it would be better to use the IDisposable interface.

Greetings, Chris


Thursday, January 24, 2019 1:29 PM

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static System.Console;

namespace LyfeCicleObject
{
    class Program : IDisposable
    {
        public Program()
        {
            WriteLine("Cons called");
        }

        public void Dispose()
        {
            WriteLine("Dispose called");
        }

        static void Main(string[] args)
        {
            WriteLine("Main started");

            using (Program p1 = new Program())
            {
                WriteLine("Block started");
                Program p2 = new Program();
                WriteLine("Block ended");
            }

            WriteLine("Main ended");
        }

    }
}

Thursday, January 31, 2019 5:43 AM

Hi,

you want the destructor to be invoked if you leave the scope? Maybe it would be better to use the IDisposable interface.

Greetings, Chris

This is a huge rubbish# proposal!

First- a destructor/finalizer is completely distinct from IDisposable interface, and therefore, the latter is not a replacement for the former. Many times, both are necessary.

Second- The former happens after the related object gets out of scope, and before the program exits!

Third- IDisposable interface is deterministic - you must call Dispose() on the object instance!

Fourth- If it was true that the destructor/finalizer were not working correctly, the correct would be to file a bug report, and not , propose to use IDisposable interface.

Fifth- the OP's supposition about the destructor/finalizer is incorrect!


Thursday, January 31, 2019 9:47 AM

@MrRubbishCSharp aka ritehere,

I would like to discuss this with you, but there is no reason to do it, I guess you will not get what I mean, It's always the same in every thread with you...

First: yes but why you say that? It's not asked.

Second: no, the destructor is NOT called when you leave the scope.

Third: No, use using blocks and you don't have to call it by yourself...

Fifth: yes you got it! But you still didn't understand my intention?!?!? -.- OMG

RIDICULOUSLY ... I don't know -.-

Please just extend your Rubbish# language, I know it's your selfmade language and you define it!

I'm always laughing about your comments on msdn. Are you a comedian? :D:D:D really funny, but in programming you may have the theoretical knowledge but snippets are mostly not really nice to see :/

Don't answer, I will not write you back in this thread if it is off topic!


Thursday, January 31, 2019 12:12 PM

@ritehere please post right here if you want to discuss it, but don't ruin this thread, too!


Saturday, February 2, 2019 4:14 AM

@MrRubbishCSharp aka ritehere

Definitely, not me. I'm ritehere44, therefore, 44 times better than the singular ritehere!

First: yes but why you say that? It's not asked.

I wrote it, to illustrate you much... much better.

Second: no, the destructor is NOT called when you leave the scope.

Please, don't lie to us! I used the prepositions after and before, and not when!

Third: No, use using blocks and you don't have to call it by yourself...

This is another rubbish# concept of yours.

First of all, there's no using block as you mentioned; you want to mean using statement

The compiler will not guess when you want to call the Dispose method; you must tell it when to call it!

In the situation above, when you close the clause body with ' } ', you are impliciting calling the Dispose() method.

Fifth: yes you got it! ...

Definitely I got it! Since decades ago...!

Fifth: ... But you still didn't understand my intention?!?!? -.- OMG

Definitely, I do!

You are trying to work around a supposedly defective destructor/finalizer with a rubbish# proposal of IDisposable implementation... 

RIDICULOUSLY ... I don't know -.-

Yes, it is ridiculous to propose IDisposable implementation, just to work around a supposedly defective destructor/finalizer.


Saturday, February 2, 2019 4:20 AM

Well, I'm posting "ritehere".

We can run an experiment to prove the destructor/finalizer is executed, as per C# Lang Spec.

Forewarning: This experiment is very dangerous, because it involves raising an exception 

at the verges of an application, therefore, do expect disastrous consequences!

For this reason, 

you are not allowed to run this experiment if you are under 69 years old, unless 

you are monitored by your parents (experienced people is required because they know what 

actions to take in case disastrous consequences that might happen)!

The code to be used,is exactly the code posted by the OP (maybe you need to add a closing clause), with one statement added:

                throw new Exception("OOOMMMMMMGGGGGGGGG!");

~Program()
{
    WriteLine("Destructor called");           
    throw new Exception("OOOMMMMMMGGGGGGGGG!");
}

Before running the code have handy, a high quality film maker camera.

Now, when you're ready, run the experiment (press Ctrl-F5 or whatever necessary).

Stare at the monitor, and see the message printed on the screen, by the exception raised!

Hear the rumbling sound! It's caused the exception being raised at the verges of an application!

Feel the test environment room, trembling! It's the earthquake happening!

Hear the gloob-gloob sound! It's the tsunami flooding the environment room!

Grab the film maker camera, and find a way to look up at the sky, and look for some "strange" lights. According to the conspiracy theorists, the lights "are" aliens spaceships monitoring the disastrous event.

Film them! They are the proof that the destructor/finalizer runs as expected.