Junior — Middle
Can you give an example of a situation where the IDisposable pattern is used for resource management?
sobes.tech AI
Answer from AI
The IDisposable pattern is used for managing unmanaged resources such as file handles, network connections, streams, etc. Its purpose is to ensure the release of resources when the object is no longer needed.
Example: working with a file. The FileStream class implements IDisposable to close the file and release the handle after use.
using (var stream = new FileStream("file.txt", FileMode.Open))
{
// Working with the file
}
// Here, stream.Dispose() is called automatically, and the file is closed
Using the using statement guarantees that Dispose is called even if an exception occurs.