Junior — Middle
Why is it important to manage memory release manually in some cases?
sobes.tech AI
Answer from AI
In C#, the garbage collector (GC) automatically frees unused memory. However, in some cases, manual memory management is important:
- When an object uses unmanaged resources (files, network connections, handles) that are not controlled by the GC.
- To release resources promptly to avoid leaks and locks.
This is done by implementing the IDisposable interface and the Dispose() method, where resources are explicitly released.
Example:
class FileHandler : IDisposable
{
private FileStream _fileStream;
public FileHandler(string path) {
_fileStream = new FileStream(path, FileMode.Open);
}
public void Dispose() {
_fileStream?.Dispose();
}
}
Thus, manual memory management is important for resource control and preventing performance and stability issues.