System Namespace
public interface IDisposable
Defines a method to release unmanaged resources.
Implement this interface in your class to provide a deterministic way to release resources. Resources that are not managed by the garbage collector, such as file handles, database connections, or graphics handles, must be explicitly released when no longer needed. The Dispose() method provides a mechanism for this explicit release.
IDisposable object.
void Dispose()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
The primary use of this method is to release unmanaged resources. Common scenarios include closing file streams, releasing network connections, and freeing memory allocated outside the .NET managed heap. It's crucial to call Dispose() when you are finished with an object that implements IDisposable to prevent resource leaks.
Consider using a using statement (or Using in Visual Basic) in C# to ensure that Dispose() is called automatically, even if exceptions occur.
Example:
using (StreamReader reader = new StreamReader("myfile.txt"))
{
string line = reader.ReadLine();
// Process the line
} // reader.Dispose() is automatically called here