I am trying to return an SqlXml object from a method which initializes it using a method local memory stream. I.e.
using (Stream memoryStream = new MemoryStream())
{
using (XmlWriter writer = XmlWriter.Create(memoryStream, new XmlWriterSettings { OmitXmlDeclaration = true }))
{
serializer.Serialize(writer, myList.ToArray(), ns);
return new SqlXml(memoryStream);
}
}
Now the method that calls it and tries to access it's fields fails with an object disposed exception
.
I gave a quick glance at SqlXml.cs and saw it is just keeping an reference to the stream which describes the behaviour.
public SqlXml(Stream value) {
// whoever pass in the stream is responsible for closing it
// similar to SqlBytes implementation
if (value == null) {
SetNull();
}
else {
firstCreateReader = true;
m_fNotNull = true;
m_stream = value;
}
I would really like to avoid caller having to pass the stream and being responsible for it's lifetime. Is there any other way to fully initializing the SqlXml object and safely disposing the memory stream?
edit:
One possible solution is to have a temp SqlXml variable and then use it to initialize return object via create reader constructor:
using (Stream memoryStream = new MemoryStream())
{
using (XmlWriter writer = XmlWriter.Create(memoryStream, new XmlWriterSettings { OmitXmlDeclaration = true }))
{
serializer.Serialize(writer, myList.ToArray(), ns);
SqlXml s = new SqlXml(memoryStream);
return new SqlXml(s.CreateReader());
}
}
But this still looks a bit clunky to me.