Search code examples
c#c++usingraii

Is there a better deterministic disposal pattern than nested "using"s?


In C#, if I want to deterministically clean up non-managed resources, I can use the "using" keyword. But for multiple dependent objects, this ends up nesting further and further:

using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
    using (BufferedStream bs = new BufferedStream(fs))
    {
        using (StreamReader sr = new StreamReader(bs))
        {
            // use sr, and have everything cleaned up when done.
        }
    }
}

In C++, I'm used to being able to use destructors to do it like this:

{    
    FileStream fs("c:\file.txt", FileMode.Open);
    BufferedStream bs(fs);
    StreamReader sr(bs);
    // use sr, and have everything cleaned up when done.
}

Is there a better way in C# to do this? Or am I stuck with the multiple levels of nesting?


Solution

  • You don't have to nest with multiple usings:

    using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
    using (BufferedStream bs = new BufferedStream(fs))
    using (StreamReader sr = new StreamReader(bs))
    {
        // all three get disposed when you're done
    }
    

    In .NET Core, there's a new using statement which allows you to dispense with the parentheses, and the disposal happens at the end of the current scope:

    void MyMethod()
    {
        using var fs = new FileStream("c:\file.txt", FileMode.Open);
        using var bs = new BufferedStream(fs);
        using var sr = new StreamReader(bs);
        // all three are disposed at the end of the method
    }