Search code examples
c#garbage-collectionidisposable

Passing IDisposable as parameter


In the following, I'm passing a disposable object as a parameter in a constructor, then doing a few operations and that's it. The constructor does nothing other than set a local variable instance of DisposableObject.

Am i right in believing the disposable will still get disposed even in the result of an exception in the Whatever() call?

If the code was in a for loop both objects would also go out of scope and get garbage collected as well (I can only have one instance of this IDisposable class in my App Domain).

using (var disposableObject = new DisposableObject()) 
{
    var simpleObject= new Simple(disposableObject);
    simpleObject.Whatever();
}

Solution

  • Just to clarify: IDisposable isn't about garbage collection, but instead about the larger topic of resource management. A simple example might be a SqlConnection which is disposed to release the connection to the database. The SqlConnection object still lives in memory and is garbage collected after it has fallen out of scope.

    This won't help with your "one-instance-per-AppDomain" problem, since the lifetime of the object is not controlled by you. At best you can have one non-disposed object.


    A using statement is effectively a try-finally block, where the finally always runs to make sure the object is disposed.

    This code:

    using(var disposable = new DisposableObject())
    {
        ...
    }
    

    essentially is the equivalent to this code:

    var disposable = new DisposableObject();
    
    try
    {
        ...
    }
    finally
    {
        disposable?.Dispose();
    }
    

    Dispose is always called, unless the reference to the object is lost.