Junior — Middle
What is the goal of using the Dispose method in resource management?
sobes.tech AI
Answer from AI
The Dispose method in C# is used for explicitly releasing unmanaged resources, such as file handles, database connections, network sockets, etc. Its purpose is to prevent resource leaks and ensure timely release of memory and other system resources.
A class implementing the IDisposable interface must implement the Dispose method, which is called when the object is no longer needed. This is especially important because the garbage collector only manages managed memory and does not free unmanaged resources.
Example of usage:
using System;
using System.IO;
class Example {
public void ReadFile(string path) {
using (var stream = new FileStream(path, FileMode.Open)) {
// Work with the file
} // Dispose is automatically called here for stream
}
}
In this example, using guarantees the call to Dispose on the FileStream object, which releases the file handle.