Do I need to implement a Dispose method?

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

Jon Skeet [C# MVP]

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

wh

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

Jon Skeet [C# MVP]

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.
 

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