/* Design an option driven program to demonstrate following garbage collection
activities
a) Number of generations
b) Generation number of target object
c) Number of bytes allocated */
using System;
class GarbageCollectionDemo
{
static void Main()
{
// Allocate objects in Generation 0
ObjectGenerationDemo();
// Explicitly trigger garbage collection and check stats
GC.Collect();
PrintGarbageCollectionStats();
}
static void ObjectGenerationDemo()
{
// Allocate objects in Generation 0
for (int i = 0; i < 10; i++)
{
var obj = new MyObject();
Console.WriteLine($"Object created in Generation {GC.GetGeneration(obj)}");
}
}
static void PrintGarbageCollectionStats()
{
Console.WriteLine("\nGarbage Collection Stats:");
Console.WriteLine($"Number of Generations: {GC.MaxGeneration + 1}");
Console.WriteLine($"Generation of Target Object: {GC.GetGeneration(new MyObject())}");
Console.WriteLine($"Total Bytes Allocated: {GC.GetTotalMemory(false)} bytes");
}
}
class MyObject
{
// Some properties or methods for demonstration purposes
public int Value { get; set; }
// You can add more properties or methods as needed
}