Return an object created by USING

后端 未结 9 1499
南方客
南方客 2021-01-18 05:32

I am creating an object(obj below) in using and return that object as part of the function return.Will this cause any problem like object will be disposed before I try to us

相关标签:
9条回答
  • 2021-01-18 05:58

    The object will be Dispose()-d when it goes out of scope, whether by return or some other codepath. The sole purpose of using is to provide a failsafe mechanism for IDisposable objects of local scope to get cleaned up whatever happens in the enclosed block of code.

    That's going to result in problems in your calling function, so don't do this.

    0 讨论(0)
  • 2021-01-18 05:58

    You would get an exception in the consumer of your object saying object is disposed as essentially that's what the using scope dose - calls the IDisposable implementation.

    0 讨论(0)
  • 2021-01-18 06:01

    Yep, this will cause problems. If you have this case (I could think of a method returning a database accessor class) don't use a using block, as you aren't responseable for the disposal of this object, but the caller is.

    0 讨论(0)
提交回复
热议问题