title: Returning SqlXml initialized with memory stream
body: <p>I am trying to return an SqlXml object from a method which initializes it using a method local memory stream. I.e.</p>
  
  <pre><code>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);
              }
          }
  </code></pre>
  
  <p>Now the method that calls it and tries to access it's fields fails with an <code>object disposed exception</code>.</p>
  
  <p>I gave a quick glance at <a href="http://referencesource.microsoft.com/#System.Data/data/System/Data/SQLTypes/SqlXml.cs" rel="nofollow">SqlXml.cs</a> and saw it is just keeping an reference to the stream which describes the behaviour.</p>
  
  <pre><code>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;
              }
  </code></pre>
  
  <p>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?</p>
  
  <p>edit:</p>
  
  <p>One possible solution is to have a temp SqlXml variable and then use it to initialize return object via create reader constructor:</p>
  
  <pre><code>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());
              }
          }
  </code></pre>
  
  <p>But this still looks a bit clunky to me.</p>