Introduction:
This
article is about understanding the working concept of destructor in C#. I know
you all may be thinking why a dedicated article on simple destructor
phenomenon. As you read this article you will understand how different is C#
destructor are when compared to C++ destructors.
- It's a special method that cleans up resources when an object is destroyed.
- Automatically called by GC before an object is removed from memory.
- Cannot be called manually.
In simple terms a destructor is a member that implements the actions required to destruct an instance of a class. The destructors enable the runtime system, to recover the heap space, to terminate file I/O that is associated with the removed class instance, or to perform both operations. For better understanding purpose I will compare C++ destructors with C# destructors.
Generally in C++ the destructor is called when objects gets destroyed. And one can explicitly call the destructors in C++. And also the objects are destroyed in reverse order that they are created in. So in C++ you have control over the destructors. One may be thinking how C# treats the destructor. In C# you can never call them, the reason is one cannot destroy an object. So who has the control over the destructor (in C#)? It’s the .Net frameworks Garbage Collector (GC).
Now
few questions arise why GC should control destructors why not us?
The
answer is very simple. GC can do better object release than a human does. If we do
manual memory management one has to take care both allocation and de-allocation
of memory. So there is always chance that one can forgot de-allocation. And
also manual memory management is time consuming and complex process. So let’s
understand why C# forbids you from explicitly writing code for
destructors.
- If we are accessing unmanaged code usually we forget to destroy an object. This avoids the destructor call and memory occupied by the object will never get released.Let examine this case by taking example, below figure shows that Memory stacks in which application XYZ loads an unmanaged code of 30 bytes.When applications XYZ ends imagine it forgot to do destroy an object in Unmanaged code so what happens is Application XYZ memory gets de allocated back to the heap but unmanaged code remains in memory. So Memory gets wasted.
- If we are trying
to release the object while object is still doing some process or I mean
object is still active.
- If we are trying to release the object that is already been released.
Understanding the complete working of Garbage collector (GC) is a big topic. But I will cover the some its details with respect to our topic. GC is a .net framework thread, which runs when needed or when other threads are in suspended mode. So first GC creates the list of all the objects created in the program by traversing the reference fields inside the objects. This list helps the GC to know how many objects it needs to keep track. Then it ensures that there are no circular references inside this list. In this list GC then checks for all the objects, which have destructor, declared and place them in another list called Finalization List.
So now GC creates two threads one, which are reachable list and another unreachable, or finalization List. Reachable objects are cleared one by one from the list and memory occupied by these objects are reclaimed back. The 2nd thread, which reads the finalization lists and calls, the each object finalized in separate object.
Let’s see how C# compiler understands the destructor code. Below is a small class created in visual studio .Net, I have created a class called MyDemoClass which has a constructor and a destructor.
So now GC creates two threads one, which are reachable list and another unreachable, or finalization List. Reachable objects are cleared one by one from the list and memory occupied by these objects are reclaimed back. The 2nd thread, which reads the finalization lists and calls, the each object finalized in separate object.
Let’s see how C# compiler understands the destructor code. Below is a small class created in visual studio .Net, I have created a class called MyDemoClass which has a constructor and a destructor.
Example: Garbage Collector
using System;
class TestGC
{
public TestGC()
{
Console.WriteLine("Object created");
}
~TestGC()
{
Console.WriteLine("Destructor called, object destroyed");
}
}
class Program
{
static void Main()
{
TestGC obj = new TestGC();
// Set reference to null
obj = null;
// Force Garbage Collection (Not recommended in real-world use)
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("End of Main");
}
}
Output:
Object created
Destructor called, object destroyed
End of Main
Destructor in C# (.NET) Example:
~ClassName()
{
// Cleanup code
}
Important Notes:
- You cannot define parameters in a destructor
- You cannot overload it.
- Only one destructor is allowed per class.
- It is used only for unmanaged resources (like file handles, DB connections, etc.) — otherwise use IDisposable.
Examples:
using System;
class FileHandler
{
public FileHandler()
{
Console.WriteLine("FileHandler created");
}
~FileHandler()
{
Console.WriteLine("Destructor: FileHandler cleaned up");
}
}
class Program
{
static void Main()
{
FileHandler fh = new FileHandler();
fh = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("End of Main");
}
}
using
System;
namespace DestrcutorsDemo
{
/// <summary>
/// Summary description for MyDemoClass.
/// </summary>
class MyDemoClass
{
public MyDemoClass()
{
Console.WriteLine("Object created");
}
~MyDemoClass()
{
Console.WriteLine("Destructor called, object destroyed");
}
static void
Main(string[] args)
{
//
// TODO: Add code to start application here
//
MyDemoClass obj = new MyDemoClass();
}
}
}
using System;
class MyClass
{
public MyClass()
{
Console.WriteLine("Object created.");
}
~MyClass()
{
Console.WriteLine("Destructor called.");
}
}
class Program
{
static void Main()
{
MyClass obj = new MyClass();
obj = null; // Object becomes unreachable
Console.WriteLine("End of Main"); // Destructor may NOT be called yet!
// No GC.Collect() here
}
}
Object created.
End of Main
❗ You might not see "Destructor called" because GC might not run before the app exits.
So after compiling the code open the assemblies in ILDASM.EXE (Microsoft Diassembler Tool) tool and see the IL code. You will see something-unusual code. In above code the compiler automatically translates a destructor into an override of the Object.Finalize() method. In other words, the compiler translates the following destructor:
class MyDemoClass
{
~MyDemoClass(){}
}
Into
following:
In Source Code Format:
|
In IL Code Format:
|
class MyDemoClass
{ Protected override void Finalize() { try{..} finally { base.Finalize();} } } |
.method
family hidebysig virtual instance void
Finalize() cil managed { // Code size 10 (0xa) .maxstack 1 .try { IL_0000: leave.s IL_0009 } // end .try finally { IL_0002: ldarg.0 IL_0003: call instance void [mscorlib]System.Object::Finalize() IL_0008: endfinally } // end handler IL_0009: ret } // end of method Class1::Finalize |
The compiler-generated Finalize method contains the destructor body inside try block, followed by a finally block that calls the base class Finalize. This ensures that destructors always call its base class destructor. So our conclusion from this is Finalize is another name for destructors in C#.
Points to remember:
Destructors are invoked automatically, and cannot be invoked explicitly.
Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.
Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it.
Destructors cannot be used with structs. They are only used with classes.
An instance becomes eligible for destruction when it is no longer possible for any code to use the instance.
Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.
When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived.
Points to remember:
Destructors are invoked automatically, and cannot be invoked explicitly.
Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.
Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it.
Destructors cannot be used with structs. They are only used with classes.
An instance becomes eligible for destruction when it is no longer possible for any code to use the instance.
Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.
When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived.
✅ What is finalize in C#?
Finalize is a special method used to perform cleanup on unmanaged resources before an object is garbage collected.
In C#, you don’t override Finalize() directly — instead you write a finalizer, which is the ~ClassName() syntax.
The finalizer is called by the GC, not by your code.
✅ When do you use it?
To clean up unmanaged resources (file handles, database connections, native memory) if the developer forgets to call Dispose().
Acts as a backup safety net.
✅ Important:
You don’t need a finalizer if you only use managed resources — the GC handles managed memory automatically.
Finalizers have performance cost — so they should be used only when really needed.
✅ How do you write a finalizer?
Here’s a simple example:
csharp
class MyResource
{
// Finalizer
~MyResource()
{
Console.WriteLine("Finalizer called!");
// Cleanup unmanaged resources here
}
}
When MyResource is no longer referenced:
The GC collects it.
The finalizer (~MyResource) runs before the memory is reclaimed.
✅ Practical example: Finalize + Dispose pattern
If your class uses unmanaged resources, you usually:
1️⃣ Implement IDisposable
2️⃣ Add a finalizer as a backup
3️⃣ Suppress finalization if Dispose is called manually.
Example:
csharp
class MyResource : IDisposable
{
private bool _disposed = false;
// Finalizer
~MyResource()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this); // Tell GC no need to call finalizer
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Free managed resources here
Console.WriteLine("Managed resources cleaned up");
}
// Free unmanaged resources here
Console.WriteLine("Unmanaged resources cleaned up");
_disposed = true;
}
}
}
✅ Dispose() → called by developer: cleans managed + unmanaged
✅ Finalizer (~MyResource) → fallback: cleans unmanaged only
✅ GC.SuppressFinalize(this) → skip finalizer if you’ve cleaned up manually.
✅ One-liner takeaway
A finalizer (~ClassName()) lets an object clean up unmanaged resources if the developer forgets to do it — it’s a backup safety net run by the GC.
⚡️ Key points
Never call a finalizer yourself.
Finalizers are non-deterministic — you don’t know when they’ll run.
Prefer IDisposable → always use using or Dispose() for deterministic cleanup.
(Practice Makes a Man Perfect)
No comments:
Post a Comment