Hiren Visavadiya
Hiren Visavadiya

Reputation: 485

About memory occupying in .net

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

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503140

Yes, you can absolutely use

return writer.ToString()
  • There's no need to flush a StringWriter
  • There actually no need to dispose it usually... but it's generally a good idea to dispose of all IDisposable implementations anyway

The 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

Related Questions