Using Interface to dispose and null and object

D

Daniel Jeffrey

I may be on the wrong track here but I thought I could do this, but it isn't
working.

I have a class which I have used a interface to define.

This class is then inherited from, and many of them are used (conditionally)
on a form.

In order to simplify my dispose area, I thought I could use the interface to
dispose and null the items, but it doesn't seem to work.

Eg.

public interface IDataModule : IDisposable
{ ... }

class ProductsDM : Candle.DataModule, IDataModule
{ ... }

class StatusDM : Candle.DataModule, IDataModule
{ ... }


Form Code
_____________

IDataModule CurrentModule;


Load method...

switch (SetupMode)
{
case SetupFormMode.SETUP_PRODUCTS:
{
ProductsModule = new DataModules.ProductsDM(....);
CurrentModule = ProductsModule;
}
break;
case SetupFormMode.SETUP_STATUSES:
{
StatusModule = new DataModules.StatusDM(....);
CurrentModule = StatusModule;
}
break;

}


Unload Method
if (CurrentModule != null)
CurrentModule.Dispose();
CurrentModule = null;


Now if I put a watch on CurrentModule and the Actually objects, the
CurrentModule is null, but the others are fine.

Any help would be great.

Daniel
 
J

Jon Skeet [C# MVP]

Daniel Jeffrey said:
I may be on the wrong track here but I thought I could do this, but it isn't
working.

I have a class which I have used a interface to define.

This class is then inherited from, and many of them are used (conditionally)
on a form.

In order to simplify my dispose area, I thought I could use the interface to
dispose and null the items, but it doesn't seem to work.

It will work fine, but you haven't posted enough code for us to work
out what the probem is. Are ProductsModule and StatusModule definitely
non-null?
 
D

Daniel Jeffrey

yes correct
after I make the calls to dispose the CurrentModule and set to null the
ProductsModule is still not null and I can browse its properties etc.

What other code would you like?

Thanks for your help.

Dan
 
L

Lasse Vågsæther Karlsen

Daniel said:
I have attached what I hope is a short but complete example.

As you will see when you click the buttons on the form, it should clear
the previous reference from CurrentModule and create the new one.

If you add a watch on the modules you will see this is not the case.

Daniel

What you have are two (three, but think of CurrentModule + one of the
other two) individual reference variables. Setting one to null won't
clear the other one. That they happen to reference the same object
doesn't matter.

If you need to keep track of the object in multiple variables, you need
to clear out the multiple variables as well.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top