Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return an object created by USING

Tags:

c#

using

dispose

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 use returned value in another function ?

using (MyObject obj = new MyObject())
{
   .
   .
   .
   return obj;
}
like image 881
aziz Avatar asked Nov 19 '10 19:11

aziz


2 Answers

Will this cause any problem like object will be disposed before I try to use returned value in another function?

Yes.

Can you explain what you're trying to do here? This code doesn't make any sense. The whole point of "using" is that you are using the object here only and then automatically getting rid of its scarce unmanaged resources, rendering it unusable. There is probably a better way to do what you want to do.

like image 79
Eric Lippert Avatar answered Oct 23 '22 21:10

Eric Lippert


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.

like image 36
Steve Townsend Avatar answered Oct 23 '22 20:10

Steve Townsend