Force Garbage Collection in C#

This tutorial will discuss the method to force the garbage collection in C#.

Force Garbage Collection With the GC.Collect() Method in C

The GC.Collect() method in C# carries out forced garbage collection. The GC.Collect() method reclaims all the inaccessible memory. With this method, all objects that are in memory are considered for cleaning. But, the objects referenced in a managed piece of code are not considered for cleaning.

using System;

namespace randomize_array
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] i = new int[100000];
            GC.Collect();
        }
    }
}

In the above code, we first generated some unused garbage in the memory with the int[] i = new int[100000] line and then force the garbage collector to collect the garbage and free up all the memory with the GC.Collect() method in C#.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.