I have the following method which creates instances of objects that are disposable.
Public Overridable Sub TransformXmlDocumentsToFileStream(ByVal stream As System.IO.Stream, ByVal xmlDocuments As IEnumerable(Of String), ByVal transformContext As XslTransformContext)
Dim readers As IEnumerable(Of XmlReader) = _
(From document In xmlDocuments _
Select XmlReader.Create(New System.IO.StringReader(document)))
With transformContext
TransformXmlDocumentsToFileStream(stream, readers, transformContext)
End With
End Sub
I then iterate over the objects in another method:
For Each reader In readers
Using reader
transform.Transform(reader, writer)
End Using
Next
The visual studio code analyzer is giving the warning:
CA2000 : Microsoft.Reliability : In method ‘TransformHelper.TransformXmlDocumentsToFileStream(Stream, IEnumerable(Of String), XslTransformContext)’, object ‘New StringReader(document)’ is not disposed along all exception paths. Call System.IDisposable.Dispose on object ‘New StringReader(document)’ before all references to it are out of scope.
Since there is no reference to the StringReader, I cannot put it in a using block or otherwise dispose it. Is it OK to just ignore this warning? The StringReader should be disposed when the reader goes out of scope and is garbage collected, correct?
Sorry for the answer in c#. A simple way to manage IDisposables is to make the method that calls new, also call Dispose.