Nesting 'IDisposable's in a single 'using' statement

后端 未结 3 1593
星月不相逢
星月不相逢 2021-01-18 10:48

Quick question about using nested disposables in a single \'using\' statement: Should I write out each disposable\'s using statement, or can I nest them into one? Example:

3条回答
  •  醉梦人生
    2021-01-18 11:01

    It depends on the constructor, GZipStream disposes of the stream you passed in when you dispose of it unless you use one of the overloads that takes in a bool and you pass in true to leaveOpen.

    However you do run a risk doing this. If GZipStream throws a ArgumentException because the CanRead property of the stream is false the passed in stream does not get disposed of.

    Personally I rather not depend on "something not going wrong" and instead usually code defensively and use the 3 statement version.


    Edit: Just to be clear, I'm not asking about nesting using statements. I'm asking whether or not an IDisposable that is created inside another IDisposable's 'using' statement will be disposed of at the end of the block. Any explanation on why or why not would be appreciated.

    If that is your question then the answer is: No, only the object declared that was assigned to (using var whatever = ...) will be disposed, any other objects created are dependent on the code of whatever the "outer" object is to be implemented to "chain call" the Dispose() methods.

提交回复
热议问题