GC::GetGeneration Method (Object^)

 

Returns the current generation number of the specified object.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

public:
static int GetGeneration(
	Object^ obj
)

Parameters

obj
Type: System::Object^

The object that generation information is retrieved for.

Return Value

Type: System::Int32

The current generation number of obj.

Use this method to determine the age of an object, and then use that information with the Collect method to force the garbage collector to collect objects in the same generation. For example, use this method when you have a set of objects that are created as a group and that become inaccessible at the same time.

The following example demonstrates how to use the GetGeneration method to determine the age of an object. The example then performs garbage collections to clean up memory and compare the pre and post collection memory totals in the console.

using namespace System;
const long maxGarbage = 1000;
ref class MyGCCollectClass
{
public:
   void MakeSomeGarbage()
   {
      Version^ vt;
      for ( int i = 0; i < maxGarbage; i++ )
      {

         // Create objects and release them to fill up memory
         // with unused objects.
         vt = gcnew Version;

      }
   }

};

int main()
{
   MyGCCollectClass^ myGCCol = gcnew MyGCCollectClass;

   // Determine the maximum number of generations the system
   // garbage collector currently supports.
   Console::WriteLine( "The highest generation is {0}", GC::MaxGeneration );
   myGCCol->MakeSomeGarbage();

   // Determine which generation myGCCol object is stored in.
   Console::WriteLine( "Generation: {0}", GC::GetGeneration( myGCCol ) );

   // Determine the best available approximation of the number
   // of bytes currently allocated in managed memory.
   Console::WriteLine( "Total Memory: {0}", GC::GetTotalMemory( false ) );

   // Perform a collection of generation 0 only.
   GC::Collect( 0 );

   // Determine which generation myGCCol object is stored in.
   Console::WriteLine( "Generation: {0}", GC::GetGeneration( myGCCol ) );
   Console::WriteLine( "Total Memory: {0}", GC::GetTotalMemory( false ) );

   // Perform a collection of all generations up to and including 2.
   GC::Collect( 2 );

   // Determine which generation myGCCol object is stored in.
   Console::WriteLine( "Generation: {0}", GC::GetGeneration( myGCCol ) );
   Console::WriteLine( "Total Memory: {0}", GC::GetTotalMemory( false ) );
}

Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1
Windows Phone Silverlight
Available since 7.1
Return to top
Show: