.NET - Replacing nested using statements with single using statement

后端 未结 5 797
说谎
说谎 2021-01-12 19:08

If you came across some C# code like this with nested using statements/resources:

using (var response = (HttpWebResponse)request.GetResponse())
{
    using (         


        
5条回答
  •  广开言路
    2021-01-12 19:42

    FWIW, here's another way to spell your original example which may satisfy any dismay over nesting:

    using (var response = (HttpWebResponse)request.GetResponse())
    using (var responseStream = response.GetResponseStream())
    using (var reader = new BinaryReader(responseStream))
    {
        // do something with reader
    }
    

    Whether the reader disposes of the stream is really a function of the reader, not the 'using'. As I recall that is often what the behavior with readers is--they take ownership of the stream and dispose of it when the reader is itself closed. But the form I've provided above should be fine.

提交回复
热议问题