c# destructors not called

David Stobbe 1 Reputation point
2022-09-05T02:51:57.377+00:00

Based on similar question responded to on Wednesday, January 23, 2019 10:08 PM, running the code attached does not call the destructors using net6, top-level or using Main. Why?

 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");  
         }  
      }  
  
   }  

//Wednesday, January 23, 2019 10:08 PM

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,218 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 24,286 Reputation points Microsoft Vendor
    2022-09-05T07:04:12.843+00:00

    @David Stobbe , Welcome to Microsoft Q&A, based on my test, I reproduced your problem.

    After checking, I find that Microsoft doc Example has explained it, the specific description as the following:

    .NET 5 (including .NET Core) or a later version: There's no output, because this implementation of .NET doesn't call finalizers when the application terminates.    
    

    Hope this could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments