Reputation: 485
Public Function GetTransformation(ByVal xmldata As String, ByVal Xsltpath As String) As String Dim writer As StringWriter = New StringWriter() Dim strXsl As String = String.Empty Try Dim xslt As New XslCompiledTransform(False) xslt.Load(Path.Combine(Application.StartupPath, Xsltpath)) Dim XmlReader As XPathDocument = New XPathDocument(New StringReader(xmldata)) xslt.Transform(XmlReader, Nothing, writer) strXsl = writer.ToString() writer.Flush() writer.Dispose() Return strXsl Catch generatedExceptionName As Exception Throw End Try End Function
I have the above function to transform an xml to string. Can I Use the return statement as like below given
return writer.ToString()
instead of the below given expert of the function
strXsl = writer.ToString() writer.Flush() writer.Dispose() Return strXsl
which is right for minimize use of memory. what happened with the variables and streams and etc. which are declared in function after executing function?
Upvotes: 0
Views: 80
Reputation: 1503140
Yes, you can absolutely use
return writer.ToString()
StringWriter
IDisposable
implementations anywayThe better solution is to use a Using
statement for the writer, so it always gets disposed. Get rid of the pointless Catch
block, and just change your code to:
Public Function GetTransformation(ByVal xmldata As String, ByVal Xsltpath As String) As String
Using writer As StringWriter = New StringWriter()
Dim xslt As New XslCompiledTransform(False)
xslt.Load(Path.Combine(Application.StartupPath, Xsltpath))
Dim XmlReader As XPathDocument = New XPathDocument(New StringReader(xmldata))
xslt.Transform(XmlReader, Nothing, writer)
Return writer.ToString()
End Using
End Function
You should very rarely be calling Dispose
explicitly - you should almost always use a Using
statement instead.
Upvotes: 3