Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does XPathDocument use the memory stream it is constructed with after construction?

Tags:

c#

.net

dispose

I have code like this:

// Take the xml message and turn it into an object
var bytes = Encoding.ASCII.GetBytes(message);
var memoryStream = new MemoryStream(bytes);

XPathDocument xPathDocument = new XPathDocument(memoryStream);

I realized that I don't clean up the MemoryStream anywhere. I was just going to change it to this:

// Take the xml message and turn it into an object
var bytes = Encoding.ASCII.GetBytes(message);
var memoryStream = new MemoryStream(bytes);

XPathDocument xPathDocument;
using(memoryStream)
{
    xPathDocument = new XPathDocument(memoryStream);
}

But I was not sure if XPathDocument uses the MemoryStream internally after construction. (If so, I would need to wait and dispose it after I am all done with the XPathDocument.)

Does anyone know when I can dispose this MemoryStream?

like image 879
Vaccano Avatar asked Mar 26 '12 17:03

Vaccano


2 Answers

No that's a good change. Once the stream is loaded into the xml, you don't need it any more.

Well I hope it's good, it's remarkably similar to a lot of the code I've written. :D

like image 84
Tony Hopkinson Avatar answered Oct 12 '22 06:10

Tony Hopkinson


The entire Stream is read and load and so yes, you can Dispose the MemoryStream this way.

On the other hand, a MemoryStream doesn't really need to be Disposed, it's more the general principal. If it had been a FileStream or NetworkStream the using would have been critical.

like image 4
Henk Holterman Avatar answered Oct 12 '22 07:10

Henk Holterman