Represents a class that frees, releases, or resets unmanaged resources.
public interface IDisposable { void Dispose(); }
The IDisposable interface is used to
manage resources such as file handles, database connections, or graphics objects
that are not managed by the .NET Common Language Runtime (CLR).
When you have an object that implements IDisposable,
you should call the Dispose method when you
are finished with the object to release any unmanaged resources it holds.
The Dispose method should implement the logic
to release unmanaged resources. It is also common practice to implement
the Dispose pattern, which allows for safe disposal of objects even if
exceptions occur.
It is strongly recommended to use the using statement in C#
or the Using statement in Visual Basic when working with objects
that implement IDisposable. The using
statement guarantees that the Dispose method
is called, even if an exception is thrown.
void Dispose();Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
None
using System; using System.IO; public class MyFileHandler : IDisposable { private StreamWriter _writer; private bool _disposed = false; public MyFileHandler(string filePath) { _writer = new StreamWriter(filePath); } public void WriteLine(string line) { if (_disposed) { throw new ObjectDisposedException(this.GetType().FullName); } _writer.WriteLine(line); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { // Dispose managed resources. _writer.Dispose(); } // Free unmanaged resources here. _disposed = true; } } public void Dispose() { Dispose(true); // Suppress finalization. GC.SuppressFinalize(this); } // Destructor (finalizer) for demonstration purposes. ~MyFileHandler() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // and call the 'Dispose(bool)' method from 'Dispose()' method Dispose(disposing: false); } } public class Program { public static void Main(string[] args) { try { // Using statement ensures Dispose is called even if exceptions occur using (var handler = new MyFileHandler("output.txt")) { handler.WriteLine("Hello, World!"); handler.WriteLine("This is a test."); // The file will be closed and resources released when exiting the using block. } } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); } } }