Search code examples
c#idisposable

Dispose all IDisposables when exiting the method without using?


Perhaps I am too lazy, but nested usings in a method make the method look complicated and difficult to understand. Is there any way to make all IDisposable objects that were created in a method be automatically disposed when exiting the method due to an exception?


PS. Thank you for the feedback. I now know there is no such feature right now. But, theoretically, is the following hypothetical syntax plausible?

void SomeMethod()
{
     autodispose var com = new SQLCommand();
     ...
     autodispose var file = new FileStream();
     ....
     autodispose var something = CreateAnObjectInAMethod(); 
     ....
}

All three objects are automatically disposed when exiting the method for any reason.


Solution

  • No but you can tidy a bit like so...

    This...

    using (var conn = new SqlConnection("blah"))
    {
        using (var cmd = new SqlCommand("blah"))
        {
            using (var dr = cmd.ExecuteReader())
            {
    
            }
        }
    }
    

    Becomes...

    using (var conn = new SqlConnection("blah"))
    using (var cmd = new SqlCommand("blah"))
    using (var dr = cmd.ExecuteReader())
    {
    
    }