My class contains an object from Interop and calls a method on it which causes it to alloc stuff. It also exposes a method to free that stuff, so I expect I should call this in Dispose():
class MyClass : IDisposable
{
private DllName.ComClassName comInstance;
void SomeMethod()
{
comInstance = new DllName.ComClassName();
comInstance.AllocStuff();
}
public void Dispose()
{
comInstance.FreeThatStuff();
}
}
Now, I should expand all that to follow the Dispose pattern. I have no other disposable or unmanaged resources to release, so assuming comInstance is managed (isn't that what Interop does, wraps unmanaged into managed?), I think the pattern disolves to:
public void Dispose()
{
if (comInstance != null)
{
comInstance.FreeStuff();
comInstance = null;
}
}
Which leaks unless I explicitly call Dispose() on instances of MyClass, which would make the Dispose pattern flawed? So does that mean comInstance must be unmanaged, and the pattern disolves to:
public void Dispose()
{
DisposeComInstance();
GC.SuppressFinalize(this);
}
~MyClass()
{
DisposeComInstance();
}
private void DisposeComInstance()
{
if (comInstance != null)
{
comInstance.FreeStuff();
comInstance = null;
}
}
EDIT:
- To avoid cluttering my class with the full pattern, could I just seal my class?
- How do I know ComClassName (and in general any class) is unmanaged?