Sobes.tech
Middle

What is the Dispose method in C# and what is it used for?

sobes.tech AI

Answer from AI

The Dispose method from the IDisposable interface is designed for explicit release of unmanaged resources (such as file descriptors, database connections, network sockets, etc.) used by an object.

It guarantees immediate release of resources, unlike the garbage collector, which operates non-deterministically.

It is used in conjunction with the using statement for automatic invocation of Dispose when exiting the block.

using (StreamReader reader = new StreamReader("file.txt"))
{
    // Work with the resource (file)
} // Dispose() is called automatically

The Dispose implementation should contain logic for releasing resources and can use finalization suppression (GC.SuppressFinalize) for objects with a finalizer (Finalize or destructor), so the garbage collector does not need to perform additional actions.

public class MyResource : IDisposable
{
    private IntPtr unmanagedResource; // Example of an unmanaged resource
    private bool disposed = false;

    public MyResource()
    {
        // Initialization of unmanaged resource
        unmanagedResource = Marshal.AllocHGlobal(100);
    }

    public void Dispose()
    {
        // Implementation of IDisposable
        Dispose(true);
        // Suppress finalization if Dispose is called explicitly
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // Free managed resources if any
            }

            // Free unmanaged resources
            Marshal.FreeHGlobal(unmanagedResource);
            unmanagedResource = IntPtr.Zero;

            disposed = true;
        }
    }

    ~MyResource()
    {
        // Finalizer (destructor). Called by the garbage collector.
        // Only free unmanaged resources.
        Dispose(false);
    }
}

Used to prevent resource leaks and ensure timely release of resources.