GC.Collect in C#

Shervan360 1,661 Reputation points
2022-09-26T02:26:39.423+00:00

Hello,

I expected to see "I'm Destructor..." message in the following code because GC ran.
Could you please explain why the desctutor didn't run when I called GC.Collect explicitly?

244633-screenshot-2022-09-25-222435.png

using System;  
  
internal class Program  
{  
    static void Main(string[] args)  
    {  
        Math m = new();  
        m = null;  
        GC.Collect();  
        // Console.ReadLine();  
    }  
    class Math  
    {  
        public Math()  
        {  
            System.Console.WriteLine("Ctor...");  
        }  
        ~Math()  
        {  
            System.Console.WriteLine("I'm Destructor...");  
        }  
    }  
  
}  
Developer technologies | C#
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2022-09-26T09:16:20.793+00:00

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

    Here is some explanation.

    First, I make sure that your console app is a .NET app based on the code Math m = new();.

    Second, as the Microsoft doc finalizers said, there's no output when we used it in the NET app.

    .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.  
    

    Also, based on my test, it will not give output I'm Destructor... even if I used your code in a .NET Framework 4.8. console app.

    After checking, I find that we need to use Trace.WriteLine instead of Console.WriteLine to show the output.

    Tested result in .net framework 4.8 when using Trace.WriteLine:

    244740-image.png

    Hope my explanation 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

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.