Hello everyone,
For the following code pattern, suppose both Base class and Component class are implementing IDisposable.
In the destructor of Foo class, there is no need to call Dispose method of Base class and Component class explicitly, and they will be called automatically during the Finalize process of Foo instance?
[Code]
Class Foo : Base
{
private Component component = new Component();
~Foo()
{
// component's Dispose method will be called automatically?
// Base's Dispose method will be called automatically?
}
}
[/Code]
thanks in advance,
George
AlanPosted Apr 15, 2008, 12:05 PM
Whereas the destructor is always called automatically, the Dispose() method never is.
You either have to call it explicitly or, if you're using C#'s 'using' statement, leave the compiler to make an implicit call to it when the statement ends.
So, in your code snippet, Foo's destructor will not call component's Dispose() method unless you tell it to do so.
However, when the Foo instance is being destroyed, the system will call component's destructor (if it has one) which will call its Dispose() method if it has been programmed to do so.
Similarly, whilst Foo's destructor will implicitly call Base's destructor, the latter will not call its Dispose() method unless it has been programmed to do so.
It's always a good idea to include code in the destructor which does call the Dispose() method unless it's been called already. This ensures that resources are always released even if the programmer forgets to call Dispose(). See this link for an example of the pattern which is normally followed:
http://msdn2.microsoft.com/en-us/library/system.gc.suppressfinalize.aspx