Sobes.tech
Junior — Middle

Selgitage välja IDisposable liidese eesmärki ja kasutamist .NET

sobes.tech AI

Vastus AI-lt

The IDisposable interface in .NET is designed for releasing unmanaged resources such as files, network connections, descriptors, etc. It contains a 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"))
{
    // Working 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.