I am trying to return an SqlXml object from a method that initializes it using the methodโs 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 its fields fails with an object disposed exception .
I took a quick look at SqlXml.cs and saw that it just maintains a link to a stream that describes the behavior.
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 the caller to not transmit the stream and not be responsible for this all his life. Is there any other way to completely initialize the SqlXml object and safely delete the memory stream?
edit:
One possible solution is to have the temp SqlXml variable, and then use it to initialize the returned object using the 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 it still looks a little awkward to me.
Klark source share