Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference Between dispose() and finalize() in C#
In this article, we will understand the difference between the Dispose() and Finalize() methods in C#. Both methods are used for resource cleanup, but they serve different purposes and are invoked in different ways during the object lifecycle.
The Dispose() method provides deterministic cleanup where you control exactly when resources are freed, while Finalize() provides a safety net for cleanup that runs during garbage collection.
Syntax
Following is the syntax for implementing Dispose() method −
public class MyClass : IDisposable {
public void Dispose() {
// cleanup code
GC.SuppressFinalize(this);
}
}
Following is the syntax for implementing Finalize() method using destructor syntax −
public class MyClass {
~MyClass() {
// finalization code
}
}
Dispose() Method
This method is defined in the
IDisposableinterface.It must be invoked explicitly by the user or using
usingstatement.It provides immediate cleanup of unmanaged resources.
It can be implemented when deterministic cleanup is required.
It is declared as a
publicmethod.It executes quickly and disposes resources instantly.
Since it performs immediately, it doesn't affect application performance negatively.
Example
using System;
public class ResourceManager : IDisposable {
private bool disposed = false;
public void DoWork() {
if (disposed)
throw new ObjectDisposedException("ResourceManager");
Console.WriteLine("Doing some work with resources...");
}
public void Dispose() {
if (!disposed) {
Console.WriteLine("Dispose() called - cleaning up resources");
disposed = true;
GC.SuppressFinalize(this);
}
}
}
public class Program {
public static void Main() {
using (ResourceManager rm = new ResourceManager()) {
rm.DoWork();
} // Dispose() is called automatically here
Console.WriteLine("ResourceManager disposed");
}
}
The output of the above code is −
Doing some work with resources... Dispose() called - cleaning up resources ResourceManager disposed
Finalize() Method
It is a method that is defined in the
System.Objectclass.It is invoked automatically by the garbage collector.
It helps free unmanaged resources just before the object is destroyed.
It is implemented as a backup cleanup mechanism for unmanaged resources.
It is declared using destructor syntax (
~ClassName).It is slower compared to the
Dispose()method.Since it runs during garbage collection, it can affect application performance.
Example
using System;
public class FileHandler {
private string fileName;
public FileHandler(string name) {
fileName = name;
Console.WriteLine($"FileHandler created for: {fileName}");
}
~FileHandler() {
Console.WriteLine($"Finalizer called for: {fileName}");
}
}
public class Program {
public static void Main() {
CreateFileHandler();
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("Program finished");
}
static void CreateFileHandler() {
FileHandler fh = new FileHandler("test.txt");
} // fh goes out of scope here
}
The output of the above code is −
FileHandler created for: test.txt Finalizer called for: test.txt Program finished
Implementing Both Dispose and Finalize Pattern
Example
using System;
public class ManagedResource : IDisposable {
private bool disposed = false;
private string resourceName;
public ManagedResource(string name) {
resourceName = name;
Console.WriteLine($"Resource '{resourceName}' acquired");
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
if (!disposed) {
if (disposing) {
Console.WriteLine($"Dispose() - Resource '{resourceName}' cleaned up");
} else {
Console.WriteLine($"Finalizer - Resource '{resourceName}' cleaned up");
}
disposed = true;
}
}
~ManagedResource() {
Dispose(false);
}
}
public class Program {
public static void Main() {
using (ManagedResource r1 = new ManagedResource("Resource1")) {
// r1 will be disposed automatically
}
ManagedResource r2 = new ManagedResource("Resource2");
// r2 will be finalized by garbage collector
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("Program completed");
}
}
The output of the above code is −
Resource 'Resource1' acquired Dispose() - Resource 'Resource1' cleaned up Resource 'Resource2' acquired Finalizer - Resource 'Resource2' cleaned up Program completed
Comparison
| Aspect | Dispose() | Finalize() |
|---|---|---|
| Interface | IDisposable interface | System.Object class |
| Invocation | Called explicitly by user | Called automatically by GC |
| Access Modifier | Public | Protected (destructor syntax) |
| Performance | Fast and immediate | Slower, affects GC performance |
| Timing | Deterministic | Non-deterministic |
| Purpose | Primary cleanup mechanism | Backup safety net |
Conclusion
The Dispose() method provides immediate, deterministic cleanup and should be your primary resource management approach. The Finalize() method serves as a backup cleanup mechanism that runs during garbage collection. For robust resource management, implement both using the standard dispose pattern with GC.SuppressFinalize() to optimize performance.
