๐งน Clean Up Resources Properly
Files, database connections, network streams need cleanup. IDisposable ensures proper cleanup. Prevent memory leaks.
๐ Implementing IDisposable
public class ResourceHandler : IDisposable
{
private bool _disposed = false;
private FileStream _fileStream;
private SqlConnection _connection;
public ResourceHandler(string filePath, string connectionString)
{
_fileStream = File.OpenRead(filePath);
_connection = new SqlConnection(connectionString);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
// Dispose managed resources
_fileStream?.Dispose();
_connection?.Dispose();
}
// Dispose unmanaged resources (if any)
_disposed = true;
}
~ResourceHandler()
{
Dispose(false);
}
}
๐ฏ Using IDisposable
// With using statement (automatic disposal)
using (var resource = new ResourceHandler("data.txt", connectionString))
{
// Use resource
} // Dispose called automatically
// Using declaration (C# 8)
using var resource = new ResourceHandler("data.txt", connectionString);
// Use resource
// Dispose at end of scope
// Manual disposal
var resource = new ResourceHandler("data.txt", connectionString);
try
{
// Use resource
}
finally
{
resource.Dispose();
}
๐ก Best Practices
- Implement IDisposable for resources (files, connections, streams)
- Use using statement for automatic disposal
- Implement finalizer for unmanaged resources
- Call GC.SuppressFinalize in Dispose
- Avoid finalizers when possible (use SafeHandle)
“IDisposable ensures resources are cleaned up. No memory leaks. Essential for file and database operations.”
