<p>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:</p>

<pre><code>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.
        }
    }
}
</code></pre>

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

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

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

[{'answer_id': 75741, 'author': 'Abe Heidebrecht', 'author_id': 9268, 'author_profile': 'https://Stackoverflow.com/users/9268', 'pm_score': -1, 'selected': False, 'text': "<p>The using statement is syntactic sugar that converts to:</p>\n\n<pre><code>   try\n   {\n      obj declaration\n      ...\n   }\n   finally\n   {\n      obj.Dispose();\n   }\n</code></pre>\n\n<p>You can explicitly call Dispose on your objects, but it won't be as safe, since if one of them throws an exception, the resources won't be freed properly.</p>\n"}, {'answer_id': 75751, 'author': 'Greg Hurlman', 'author_id': 35, 'author_profile': 'https://Stackoverflow.com/users/35', 'pm_score': 1, 'selected': False, 'text': "<p>Instead of nesting using statements, you can just write out the .Dispose calls manually - but you'll almost certainly miss one at some point.</p>\n\n<p>Either run FxCop or something else that can make sure that all IDisposable-implementing type instances have a .Dispose() call, or deal with the nesting.</p>\n"}, {'answer_id': 75755, 'author': 'Ryan Lundy', 'author_id': 5486, 'author_profile': 'https://Stackoverflow.com/users/5486', 'pm_score': 6, 'selected': True, 'text': '<p>You don\'t have to nest with multiple usings:</p>\n\n<pre><code>using (FileStream fs = new FileStream("c:\\file.txt", FileMode.Open))\nusing (BufferedStream bs = new BufferedStream(fs))\nusing (StreamReader sr = new StreamReader(bs))\n{\n    // all three get disposed when you\'re done\n}\n</code></pre>\n'}, {'answer_id': 75761, 'author': 'Bob Wintemberg', 'author_id': 12999, 'author_profile': 'https://Stackoverflow.com/users/12999', 'pm_score': 3, 'selected': False, 'text': '<p>You can put using statements together before the opening braces like so:</p>\n\n<pre><code>  using (StreamWriter w1 = File.CreateText("W1"))\n  using (StreamWriter w2 = File.CreateText("W2"))\n  {\n      // code here\n  }\n</code></pre>\n\n<p><a href="http://blogs.msdn.com/ericgu/archive/2004/08/05/209267.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/ericgu/archive/2004/08/05/209267.aspx</a></p>\n'}, {'answer_id': 75764, 'author': 'JeffFoster', 'author_id': 9853, 'author_profile': 'https://Stackoverflow.com/users/9853', 'pm_score': 2, 'selected': False, 'text': '<p>You could use this syntax to condense things down a bit:</p>\n\n<pre><code>using (FileStream fs = new FileStream("c:\\file.txt", FileMode.Open))\nusing (BufferedStream bs = new BufferedStream(fs))\nusing (StreamReader sr = new StreamReader(bs))\n{\n}\n</code></pre>\n\n<p>This is one of those rare occasions where not using { } for all blocks makes sense IMHO.</p>\n'}, {'answer_id': 75778, 'author': 'Paul van Brenk', 'author_id': 1837197, 'author_profile': 'https://Stackoverflow.com/users/1837197', 'pm_score': 0, 'selected': False, 'text': '<p>you can omit the curly braces, like:</p>\n\n<pre><code>using (FileStream fs = new FileStream("c:\\file.txt", FileMode.Open))\nusing (BufferedStream bs = new BufferedStream(fs))\nusing (StreamReader sr = new StreamReader(bs))\n{\n        // use sr, and have everything cleaned up when done.\n}\n</code></pre>\n\n<p>or use the regular try finally approach:</p>\n\n<pre><code>FileStream fs = new FileStream("c:\\file.txt", FileMode.Open);\nBufferedStream bs = new BufferedStream(fs);\nStreamReader sr = new StreamReader(bs);\ntry\n{\n        // use sr, and have everything cleaned up when done.\n}finally{\n   sr.Close(); // should be enough since you hand control to the reader\n}\n</code></pre>\n'}, {'answer_id': 75836, 'author': 'Michael Meadows', 'author_id': 7643, 'author_profile': 'https://Stackoverflow.com/users/7643', 'pm_score': 0, 'selected': False, 'text': '<p>This makes for a much larger net plus in lines of code, but a tangible gain in readability:</p>\n\n<pre><code>using (StreamWrapper wrapper = new StreamWrapper("c:\\file.txt", FileMode.Open))\n{\n    // do stuff using wrapper.Reader\n}\n</code></pre>\n\n<p>Where StreamWrapper is defined here:</p>\n\n<pre><code>private class StreamWrapper : IDisposable\n{\n    private readonly FileStream fs;\n    private readonly BufferedStream bs;\n    private readonly StreamReader sr;\n\n    public StreamWrapper(string fileName, FileMode mode)\n    {\n        fs = new FileStream(fileName, mode);\n        bs = new BufferedStream(fs);\n        sr = new StreamReader(bs);\n    }\n\n    public StreamReader Reader\n    {\n        get { return sr; }\n    }\n\n    public void Dispose()\n    {\n        sr.Dispose();\n        bs.Dispose();\n        fs.Dispose();\n    }\n}\n</code></pre>\n\n<p>With some effort, StreamWrapper could be refactored to be more generic and reusable.</p>\n'}, {'answer_id': 76587, 'author': 'Jesse C. Slicer', 'author_id': 3312, 'author_profile': 'https://Stackoverflow.com/users/3312', 'pm_score': 1, 'selected': False, 'text': '<p>I have implemented solutions like <a href="https://stackoverflow.com/questions/75722/is-there-a-better-deterministic-disposal-pattern-than-nested-usings-in-c#75836">Michael Meadows</a>\'s before, but his <code>StreamWrapper</code> code doesn\'t take into account if the <code>Dispose()</code> methods called on the member variables throw an exception for one reason or another, the subsequent <code>Dispose()</code>es will not be called and resources could dangle.  The safer way for that one to work is:</p>\n\n<pre><code>        var exceptions = new List&lt;Exception&gt;();\n\n        try\n        {\n            this.sr.Dispose();\n        }\n        catch (Exception ex)\n        {\n            exceptions.Add(ex);\n        }\n\n        try\n        {\n            this.bs.Dispose();\n        }\n        catch (Exception ex)\n        {\n            exceptions.Add(ex);\n        }\n\n        try\n        {\n            this.fs.Dispose();\n        }\n        catch (Exception ex)\n        {\n            exceptions.Add(ex);\n        }\n\n        if (exceptions.Count &gt; 0)\n        {\n            throw new AggregateException(exceptions);\n        }\n    }\n</code></pre>\n'}, {'answer_id': 78362, 'author': 'Joel Lucsy', 'author_id': 645, 'author_profile': 'https://Stackoverflow.com/users/645', 'pm_score': 0, 'selected': False, 'text': '<p>It should be noted that generally when creating stream based off another stream the new stream will close the one being passed in. So, to further reduce your example:</p>\n\n<pre><code>using (Stream Reader sr = new StreamReader( new BufferedStream( new FileStream("c:\\file.txt", FileMode.Open))))\n{\n    // all three get disposed when you\'re done\n}\n</code></pre>\n'}, {'answer_id': 6076898, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>for this example let us assume you have:</p>\n\n<p>a file named 1.xml under c:\\</p>\n\n<p>a textbox named textBox1, with the multi-line properties set ON.</p>\n\n<pre><code>const string fname = @"c:\\1.xml";\n\nStreamReader sr=new StreamReader(new BufferedStream(new FileStream(fname,FileMode.Open,FileAccess.Read,FileShare.Delete)));\ntextBox1.Text = sr.ReadToEnd();\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/75722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8701/']