2

I've just found that method in xsd dataset.

[System.Diagnostics.DebuggerNonUserCodeAttribute()]
        protected override System.Xml.Schema.XmlSchema GetSchemaSerializable() {
            global::System.IO.MemoryStream stream = new global::System.IO.MemoryStream();
            this.WriteXmlSchema(new global::System.Xml.XmlTextWriter(stream, null));
            stream.Position = 0;
            return global::System.Xml.Schema.XmlSchema.Read(new global::System.Xml.XmlTextReader(stream), null);                
        }

It creates 3 streams, but not using "using" clausule/closing them. Why is that? It also says, at the top of the file, that

//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.

So I believe I shouldn't fix it myself. Can anyone explain? :) Thanks

Patryk
  • 3,042
  • 11
  • 41
  • 83
  • a duplicate, really? – Patryk Mar 08 '16 at 11:42
  • I had no idea I had the power to have this closed with no additional voters weighing in! If you don't think it _should_ be a duplicate (I think it should be, which I discovered after my answer), explain, and I can vote to reopen. – Jacob Mar 08 '16 at 11:49

1 Answers1

1

The generated code isn't creating three streams, but rather is creating one stream, a stream writer, and a stream reader. The "stream" is just a MemoryStream, which provides a stream interface, but really is just a wrapper around a memory buffer.

Normally it makes sense to .Dispose() a stream (or use a using block) because a stream is wrapping some resource that needs to be released (like a file handle or TCP socket), and you also need to disable the stream from further use. But since this is just a MemoryStream that doesn't really manage external resources, and it just exists within the scope of this method, and there's no way that other code will have access to the stream, all .Dispose() would do is run some logic to disable the stream, which isn't really useful. So normal garbage collection would suffice for cleanup.

Note that I'm not advocating that memory streams shouldn't be disposed; it's a good idea to use a using block for any IDisposable because you don't know the implementation details and should just assume you should clean up resources when you're done with the object. But not disposing in this case could potentially be an optimization.

Edit:

The venerable John Skeet has weighed in on a similar question:

https://stackoverflow.com/a/234257/119549

Community
  • 1
  • 1
Jacob
  • 77,566
  • 24
  • 149
  • 228