views:

98

answers:

5

I want to use IDisposable interface to clean any resource from the memory, that is not being used.

public class dispose:IDisposable
{
        public void Dispose()
        {

            throw new NotImplementedException();
        }

        public void fun()
        {
            PizzaFactory _pz = new PizzaFactory();   //
        }
    }

I want to dispose pz object, when there is no ref to it exists. Please let me know how to do it.

+7  A: 

That's what the garbage collector is for. If all you're worried about is reclaiming memory, let the garbage collector do it for you. IDisposable is about reclaiming unmanaged resources (network connections, file handles etc). If PizzaFactory has any of those, then it should implement IDisposable - and you should manage its disposal explicitly. (You can add a finalizer to run at some point after there are no more live references to it, but it's non-deterministic.)

Jon Skeet
+4  A: 

That sounds more garbage collection, not IDisposable.

if _pz is disposable and needs to be disposed when the dispose instance is disposed (usually via using), you could have:

    public void Dispose()
    {
        if(_pz != null) _pz.Dispose();
        _pz = null;
    }

You can do something related with finalizers, but that is not a good idea here.

Marc Gravell
+2  A: 
public void Dispose()
{
     _pz.Dispose();
}

if PizzaFactory is not IDisposable, you don't need anything. There is the garbage collector.

onof
A: 

vaibhav - wouldn't you be implementing the IDisposable interface in order to use the using construct?? that way, it get's disposed of automatically..

jim

jim
A: 

Take a look at the standard dispose pattern.

http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx

nitroxn