O'Reilly logo

.NET Gotchas by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 5. Garbage Collection Gotchas

Garbage collection, in general, is the process of cleaning up the memory and resources used by an object when it is no longer needed. For instance, in C++, you write a destructor to take care of this. There are two tasks that the destructor typically performs:

  • deletes other objects to which the object holds pointers

  • closes handles to resources

.NET, on the contrary, provides automatic garbage collection. It largely removes the burden of memory management from the programmer. But what does automatic garbage collection really do? It just reclaims the memory used by objects. What about the cleanup of resources?

When I say resources here, I mean unmanaged resources: those that .NET will not be able to release automatically. For example, resources created while interacting with a COM component or while using PInvoke to access some Win32 API. You, the programmer, have to write code to properly dispose of these resources.

The Finalize() method is provided for this purpose. When an object is garbage-collected, the CLR takes care of memory-related cleanup and calls the object’s Finalize() method, giving it an opportunity to release any unmanaged resources.

In VB.NET, you have to actually write the Finalize() method. In C#, you don’t. Instead, you write a specialized pseudo-destructor with the ~ NameOfYourClass () syntax, as in C++. But don’t confuse the C# pseudo-destructor with the C++ destructor. The generated MSIL does not contain any destructor. The C# ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required