It depends on how the class you're using implemented the IDisposable
interface. Below is an example of how I typically implement the interface.
The problem when relying on the destructor to clean up your object when
using child objects that implement the IDisposable interface - they may have
already been disposed of by the time the destructor on your class gets
called. Which is why whenever an object implements IDisposable you're
supposed to call Dispose on your own when you're done with it to ensure
everything within the object gets cleaned up properly.
As for your example below, we were talking about the use of IDisposable -
not whether you can access child objects from an objects destructor.
Implement IDisposable in both of your classes, call dispose on the parent
object and then let the destructor try and access it. It should throw an
exception about trying to use an object that's already been disposed of.
static class Program {
static void Main(string[] args) {
using (DisposableObject o = new DisposableObject()) {
o.DoWork();
}
}
}
class DisposableObject : IDisposable {
Stream _s;
public DisposableObject() {
this._s = new MemoryStream();
}
~DisposableObject() {
this.Dispose(false);
}
public void Dispose() {
this.Dispose(true);
GC.SupressFinalize(this);
}
public void DoWork() {
}
void Dispose(bool disposing) {
if (disposing) {
this._s.Dispose();
}
}
}
<qg**********@mailinator.comwrote in message
news:ff**********************************@2g2000hs n.googlegroups.com...
In your control, override the Dispose(bool) method and handle your cleanup
there. You'll want to make sure you only handle the disposal when
disposing
is true, false gets passed to the method when the destructor gets called
by
the garbage collector. In which case if it is false, the objects you're
trying to clean up have already been released and will be null.
Hi Jeff.
Are you sure about this? Its my understanding that even if the
finalizer is being called by the garbage collector you are still able
to get a handle to the other child objects.
Of course, referencing a child object while the garbage collector is
disposing of them may be a bad idea because the object that you are
calling may have had their Dispose method already called but that
should be another story.
I put together a little sample to test this, if you run the sample
below, even if “ChildClass” get dispossed first, “ParentClass” is
still able to successfully get a reference to the “ChildClass”.
namespace ConsoleApplication393
{
class Program
{
static void Main(string[] args)
{
ParentClass m = new ParentClass();
}
}
public class ParentClass
{
ChildClass m_Caca = new ChildClass();
public ParentClass()
{
}
~ParentClass()
{
// No problems here even if "ChildClass" has been
disposed.
int o = m_Caca.SomeInt;
}
}
public class ChildClass
{
public int SomeInt = 123;
public ChildClass()
{
}
~ChildClass()
{
SomeInt = 999;
}
}
}
Is that what you meant?
Thanks.