Search code examples
c#idisposableusinginstantiation

Delayed instantiation with c# using statment


Is there any way to write a using statement without instantiating the IDisposable immediately?

For example, if I needed to do something like:

using (MyThing thing)
{
    if (_config == null)
    {
         thing = new MyThing();
    }
    else
    {
         thing = new MyThing(_config);
    }

    // do some stuff

} // end of 'using'

Is there an accepted pattern for cases like this? Or am I back to handling the IDisposable explicitly again?


Solution

  • Well, in your example you do instantiate the disposable object immediately - just based on a condition. For example, you could use:

    using (MyThing thing = _config == null ? new MyThing() : new MyThing(_config))
    {
        ...
    }
    

    To be more general, you can use a method:

    using (MyThing thing = CreateThing(_config))
    {
    }
    

    The tricky bit would be if the timing of the instantiation changed based on various conditions. That would indeed be harder to handle with a using statement, but would also suggest that you should try to refactor your code to avoid that requirement. It won't always be possible, but it's worth trying.

    Another alternative is to encapsulate the "thing" in a wrapper which will lazily create the real disposable object appropriately, and delegate to that for disposal and anything else that you can do with the type. Delegation like this can be a pain in some situations, but it might be appropriate - depending on what you're really trying to do.