2

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))
{
    ....
}
2
  • The CreateDisposable method needs to return a bool...
    – Rufus L
    Jan 6, 2020 at 22:59
  • @RufusL, I added an indicative line Jan 7, 2020 at 2:58

7 Answers 7

6

A using statement doesn't have to declare a variable. Having a disposable as an out paramter 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)
{
}
6

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.

3
  • The reason for the multiple returns is that I am returning accessors to database tables, where they all share the same database context. I could create the context and then pass it in to different factories, but that disassociates the two things, which makes it more error-prone. Jan 7, 2020 at 2:55
  • @SimonParker: If the two things are tightly bound then you might make a disposable class that encapsulates those two things, and return that. Jan 7, 2020 at 18:20
  • As usual, things are never simple. The factory is a generic factory that can generate different accessors depending on which is requested. This means returning a single disposable would require some form of magic to get the right accessor out of it. Jan 7, 2020 at 21:36
1

Put your using on the next line

CreateDisposable(out CanDispose myDispose);
using (myDispose)
{

}
1

You need to declare it first and then use it on the using statement.

CreateDisposable(out CanDispose myDispose)
using (myDispose)
{
    ....
}

You can look into this links to get more information about using

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement
https://www.c-sharpcorner.com/article/the-using-statement-in-C-Sharp/

1

Sinceusing statement is just an implementation of 'try / finally' statement, so you can just use this statement directly as the following:

   CanDispose canDispose = null;
        try
        {
            CreateDisposable(out CanDispose canDispose);
        }

        finally
        {
            canDispose?.Dispose();
        }
1

Wrapping your factory method with an adapter will let you keep the semantics that you're used to. Consistency is generally a Good Thing™

public void SomeFunction()
{
  var getInstance = () => {
    CreateDisposable( out CanDispose instance );
    return instance;
  };

  using ( var instance = getInstance() ) {
    // do something with your instance before it gets disposed.
  }

}

0

If you need multiple results

My suggestion is to use a Tuple, but it looks like you want to know if the object was created successfully, so you may want to be checking the results. In any case, using the out is going to require you to define the var on a different line.

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        var factory = new DisposableFactory();
        IDisposable d;
        var success = factory.TryGetDisposable(out d);
        if (success){
            using (d) {

            }           
        }   

        using (factory.GetDisposableResults().Item2){

        }
    }   
}

public class CanDispose : IDisposable
{
    void IDisposable.Dispose(){

    }
}

public class DisposableFactory
{
    public bool TryGetDisposable(out IDisposable d)
    {
        d = new CanDispose();
        return true;
    }

    public (bool, IDisposable) GetDisposableResults()
    {
        var tup = (true, new CanDispose());
        return tup;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.