C# FAQ: How do destructors work in CSharp?

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

How do destructors work in C#?

A destructor is a method that is called when an object is destroyed—it's memory is marked unused. C++ destructors are used to free up memory and other resources and to perform housekeeping tasks. In .NET, the Garbage Collector (GC) performs much of this type of work automatically. Generally, rather than define a destructor for manual cleanup, let the Common Language Runtime (CLR) handle it.

In C#, the Finalize method performs the operations that a standard C++ destructor might perform. Finalizers are similar to destructors except that it is not guranteed that they will be called by the CLR.

Here is a sample finalizer specification using the C++ destructor syntax which places a tilde (~) symbol before the class name:

class Test
{
   ~Test()
   {
      ...
   }
 
   public static void Main() {}
}

When defining a C# finalizer, it is not named Finalize. However, finalizers do override object.Finalize(), which is called during the garbage collection process.

See also



Personal tools