Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Using" an out parameter

Tags:

c#

Let's imagine I have a simple class that is disposable:

class CanDispose : IDisposable
{
   ...
}

Now I can obviously put this in a "using" block to make it dispose:

using (var myDisposable = new CanDispose())
{
    ...
}

But what if I have a factory method that returns the disposable via an out parameter? In my example there can be multiple returns, so multiple outs are clean:

public bool CreateDisposable(out CanDispose canDispose)
{
   canDispose = new CanDispose();
   ...
   return ret; 
}

How do I put this in a using statement? Simply putting the function call into a using block doesn't seem to work. Do I have to resort to returning a Tuple (will that work?), or is there a simpler way?

Note, this doesn't appear to work. At least it doesn't shut up the warning about disposing before going out of scope:

using (CreateDisposable(out CanDispose myDispose))
{
    ....
}
like image 665
Simon Parker Avatar asked Feb 25 '26 21:02

Simon Parker


2 Answers

A using statement doesn't have to declare a variable. Having a disposable as an out parameter is not ideal, and you should avoid it in your own code, but if you're consuming a library that does it, you can simply put the variable in the using block's expression after calling the method.

CreateDisposable(out CanDispose myDispose);
using (myDispose)
{
}
like image 190
madreflection Avatar answered Feb 27 '26 11:02

madreflection


How do I put this in a using statement?

You do not. Those two patterns -- out parameter, and automatic dispose via using -- do not compose well.

Do I have to resort to returning a Tuple (will that work?)

I note that questions of the form "will this work?" can be answered by trying it. But to save you those keystrokes: tuples are not disposable.

is there a simpler way?

Just use a using block on the out parameter; make it two statements, not one.

But your question indicates that there is a more fundamental problem here. Presumably the Boolean that is returned is meaningful. It sounds like you are planning on ignoring that Boolean and using the out parameter regardless; if that is safe to do, then just make a version that returns the value without the Boolean, since it is apparently not useful.

More generally -- the fact that you are returning two values from a factory is a code smell. Can you say more about what you are doing? There might be a better pattern to use altogether.

like image 25
Eric Lippert Avatar answered Feb 27 '26 09:02

Eric Lippert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!