Search code examples
c#idisposable

How to properly dispose locally created object in another method?


So I have a class which implements IDisposable, and I have several methods (in another class) which follow the pattern below:

public void SomeMethod()
{
    DisposableObject disposableObject = new DisposableObject();

    // Do some stuff with the object

    SomeOtherMethod(disposableObject);
    disposableObject.Dispose();
}

While all of these methods do different things, they all call SomeOtherMethod at the end, which does a few more things with the disposable object before it's no longer needed. When I move disposableObject.Dispose(); into SomeOtherMethod, Visual Studio gives me a message saying: "Use recommended dispose pattern to ensure that object created by 'new DisposableObject()' is disposed on all paths: using statement/declaration or try/finally"

This message appears regardless of whether or not I pass the disposable object to SomeOtherMethod using the ref keyword.

My question is, will that object be disposed as long as SomeOtherMethod calls Dispose() on it? I'm assuming it will, and Visual Studio continues to send the message simply because it isn't "aware" of what's happening to that object in subsequent methods, but I'd love to get some confirmation on that!


Solution

  • will that object be disposed

    Sorry, but that’s a meaningless question. The CLR does not keep track of whether an object has had its “dispose” method called or not (see Will the Garbage Collector call IDisposable.Dispose for me? )

    As a general rule, it is always much nicer (readable/ maintainable / less-bug-prone / etc) that a method that creates an issue should also be the one that cleans up after itself. As you’ve just found, this pattern also allows automated checking by the compiler - and again, it is also a good rule to ensure that your code compiles cleanly without errors OR WARNINGS.

    In this case, the warning is giving you a couple of ways to implement this cleanly; personally, I would prefer the “using” clause (so avoiding having to have an explicit call to “dispose”) like :

     public void SomeMethod()
     {
         using (DisposableObject disposableObject = new DisposableObject() )
          {
    
               // Do some stuff with the object
    
               SomeOtherMethod(disposableObject);
           }
    

    }