Sobes.tech
Junior — Middle

Explain the purpose and use of the IDisposable interface in .NET.

sobes.tech AI

Answer from AI

The IDisposable interface in .NET is designed for releasing unmanaged resources such as files, network connections, handles, etc. It contains a single method — Dispose(), which is called to explicitly release resources.

Using IDisposable allows controlling the timing of resource release, which is important for preventing memory leaks and deadlocks.

Example of usage:

class ResourceHolder : IDisposable
{
    private FileStream fileStream;

    public ResourceHolder(string filePath)
    {
        fileStream = new FileStream(filePath, FileMode.Open);
    }

    public void Dispose()
    {
        fileStream?.Dispose();
    }
}

// Usage with the using statement
using (var resource = new ResourceHolder("file.txt"))
{
    // Work with the resource
}
// Dispose() is automatically called after exiting the using block

Thus, IDisposable helps manage the lifecycle of resources and ensures their proper release.

Explain the purpose and use of the IDisposable… - sobes.tech