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!