Reputation: 34447
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
Reputation: 4789
Take a look at the standard dispose pattern.
http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx
Upvotes: 0
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
Reputation: 17377
public void Dispose()
{
_pz.Dispose();
}
if PizzaFactory is not IDisposable, you don't need anything. There is the garbage collector.
Upvotes: 3
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
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