Do I need to implement a Dispose method?

  • Thread starter Thread starter wh
  • Start date Start date
W

wh

I have a class which when instatiated creates a new XmlDocument object and
loads an xml file into it. It is used as follows:

MyObject obj = new MyObject("books.xml");

If I later have

obj = new MyObject("books2.xml");

Would all memory referenced by 'obj' (i.e. the XmlDocument) from the first
call be freed or would I be required to implement a Dispose method to
release the memory associated like:

public void Dispose()
{
m_Xml = null;
}

From what I can make out, as XmlDocument is a managed resource (with no
explicit Dispose() or Close() method) it will automatically be deallocated.

Wayne.
 
wh said:
I have a class which when instatiated creates a new XmlDocument object and
loads an xml file into it. It is used as follows:

MyObject obj = new MyObject("books.xml");

If I later have

obj = new MyObject("books2.xml");

Would all memory referenced by 'obj' (i.e. the XmlDocument) from the first
call be freed or would I be required to implement a Dispose method to
release the memory associated like:

public void Dispose()
{
m_Xml = null;
}

From what I can make out, as XmlDocument is a managed resource (with no
explicit Dispose() or Close() method) it will automatically be
deallocated.

Setting

obj = new MyObject("books2.xml"); doesn't free up memory immediately,
but then neither does m_Xml = null;

You just don't free up memory immediately in .NET - the garbage
collector takes care of it. If you've got *unmanaged* resources within
your object, or references to any objects which themselves implement
IDisposable, you should dispose of those appropriately. However, that
should be a fairly rare occurrence, IMO.
 
Thank you for your reply.

So can I assume that *if* XmLDocument did implement a Dispose() method then
I should provide a Dispose() method in my class and call the Dispose() of
the XmlDocument?

Wayne.
 
wh said:
So can I assume that *if* XmLDocument did implement a Dispose() method then
I should provide a Dispose() method in my class and call the Dispose() of
the XmlDocument?

Yes.
 
Back
Top