Junior — Middle
What is the purpose of the IDisposable interface in C# programming?
sobes.tech AI
Answer from AI
The IDisposable interface in C# is designed for releasing unmanaged resources such as file handles, database connections, network sockets, etc. It contains a single method Dispose(), which is called to explicitly release these resources when the object is no longer needed.
Using IDisposable helps prevent resource leaks and ensures that they are properly released outside of the garbage collector's work.
Example of usage:
using (var stream = new FileStream("file.txt", FileMode.Open))
{
// Working with the file
} // Here, stream.Dispose() is automatically called
In this example, using guarantees the call to Dispose(), which releases the file after use.