James Kingston Clarke

TIL You can use IDisposable to create context managers in C#

If you want to use Python-style context managers in C#, you can use the IDisposable class.

public class MyCustomContext : IDisposable
{
    private bool isDisposed = false;

    public MyCustomContext()
    {
        Console.WriteLine("Entering context");
    }

    public void Dispose()
    {
        Dispose(true);
    }
    
    protected virtual void Dispose(bool disposing)
    {
        if (isDisposed)
        {
            return;
        }

        Console.WriteLine("Exiting context");

        isDisposed = true;
    }
}

...

using(new MyCustomContext()){
    // do some work here
}