In C#, Dispose() and Finalize() are both used to
release unmanaged resources (like file handles, database connections, etc.), but they are used in
different ways and serve different purposes.
Dispose() (IDisposable Interface)
Explicit cleanup method.
Called manually by the developer to release unmanaged resources.
Belongs to the IDisposable interface.
Often used in a using block, which automatically calls Dispose().
public class Resource : IDisposable
{
private FileStream _file;
public Resource(string path)
{
_file = new FileStream(path, FileMode.Open);
}
public void Dispose()
{
_file?.Dispose(); // Free unmanaged resource
GC.SuppressFinalize(this); // Optional: tells GC not to call Finalize
}
}
Use when: You want to explicitly and deterministically release resources.
Finalize() (Destructor)
Called by the Garbage Collector (GC) when the object is no longer in use.
Cannot be called directly — handled automatically by the CLR.
Used as a safety net in case Dispose() wasn’t called.
Implemented via a destructor (~ClassName() in C#).
public class Resource
{
~Resource()
{
// Cleanup logic
}
}
Drawbacks:
Runs on GC, so timing is non-deterministic.
Expensive: keeps object in memory longer (until finalization).
Best Practice: Use Dispose() and Suppress Finalize
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In C#,
Dispose()andFinalize()are both used to release unmanaged resources (like file handles, database connections, etc.), but they are used in different ways and serve different purposes.Dispose()(IDisposable Interface)IDisposableinterface.usingblock, which automatically callsDispose().Use when: You want to explicitly and deterministically release resources.
Finalize()(Destructor)Dispose()wasn’t called.~ClassName()in C#).Drawbacks:
Best Practice: Use
Dispose()and Suppress FinalizeSummary Table
Dispose()Finalize()(Destructor)IDisposable~ClassName()