Like the Rules of Optimization, there are two rules to follow for the touching .NET's Garbage Collector: (1) Don't, and (2) Be careful (for experts only). Most memory-related problems that developers experience in .NET do not require intervention of GC, but more an injection of sane code.

Joe's coworker — and self-proclaimed expert — was getting some pesky OutOfMemoryException errors while cloning objects. Knowing that it had to be a problem with garbage collection, he concocted this innovative solution.

public static IClonable SafelyClone(IClonable a)
{
    IClonable b = a;
    for (int i = 0; i < 10; i++)
    {
        try
        {
            b = a.Clone();
            break;
        }
        catch (OutOfMemoryException)
        {
            GC.Collect(GC.MaxGeneration);
            GC.WaitForPendingFinalizers();
        }
    }
    return b;
}

Why 10? To be extra, extra, extra, extra, extra, extra, extra, extra, extra sure that there's free memory.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!