Vaibhav Jain
Vaibhav Jain

Reputation: 34447

How to use IDisposable to dispose an object

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.

Upvotes: 0

Views: 1815

Answers (5)

TrustyCoder
TrustyCoder

Reputation: 4789

Take a look at the standard dispose pattern.

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

Upvotes: 0

jim tollan
jim tollan

Reputation: 22485

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

Upvotes: 0

onof
onof

Reputation: 17377

public void Dispose()
{
     _pz.Dispose();
}

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

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1064004

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.

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1503280

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.)

Upvotes: 10

Related Questions