C# - GC.Collect() Method with Example

In this tutorial, we will learn about the GC.Collect() method with its definition, usage, syntax, and example. By Nidhi Last updated : April 03, 2023

GC.Collect() Method

The GC.Collect() method is used to execute garbage collection forcefully.

Syntax

void  GC.Collect(int genNum);

Parameter(s)

  • genNum: The number of the oldest generation to be garbage collected.

Return Value

It does not return any value.

C# program to force an immediate garbage collection

The source code to force an immediate garbage collection is given below. The given program is compiled and executed successfully.

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

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      Program pObj = new Program();
      GC.Collect(0);

      Console.WriteLine("Garbage collection done forcefully");
      Console.WriteLine();
    }
  }
}

Output

Garbage collection done forcefully

Press any key to continue . . .

C# Garbage Collection Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.