Does the using statement dispose only the first variable it create?

后端 未结 6 810
猫巷女王i
猫巷女王i 2021-01-12 15:27

Let\'s say I have a disposable object MyDisposable whom take as a constructor parameter another disposable object.

using(MyDisposable myDisposab         


        
6条回答
  •  囚心锁ツ
    2021-01-12 15:58

    Why not nest them?

    using(var outer = new AnotherDisposable())
    {
       using(var inner = new MyDisposable(outer))
       {
          //whatever
       }
    
    }
    

    Now at least you can be sure they'll be disposed off correctly.

提交回复
热议问题