There's an unofficial category of posts here that I call "Somebody told us string builders were more efficient, so we always use string builders, regardless of whether or not that actually makes sense," or STUSBWMESWAUSBROWONTAMS, for short. Probably should workshop that name some.

In any case, Adam sends us a new entry for that collection:

 Public Function ReadFromFile(ByVal filename As String) As String

    Dim sb As StringBuilder = New StringBuilder()
    Dim str As String = String.Empty

    Using sr As StreamReader = File.OpenText(filename)
        str = sr.ReadToEnd()
        sb.Append(str & Constants.vbLf)
    End Using

    Return sb.ToString()

End Function

This function takes a filename, opens a file, reads the entire contents of the file to a variable. It concatenates a line feed to the end of the string it just read, then appends all of that to a string builder. Finally, we return sb.ToString(), taking the single string in the string builder, appending nothing to it, and returning the result.

I'd almost, almost forgive the code if it was more like:

        str = sr.ReadToEnd()
        sb.Append(str)
        sb.Append(Constants.vbLf)

You're not actually gaining much from this, but it follows the broad pattern of "use a string builder" so that if you ever wanted to change the structure of the output, you're already set up to prepend/append new text in a scalable way. I'd argue that's premature abstraction, though: a simple return sr.ReadToEnd() & Constants.vbLf would do the current job.

The code that we have is a clear superstitious use of string builders. The string builder is used as a charm against poor performance, without understanding why one might use it, or how it might work; string concatenation means string builder, always and forever, "why" doesn't enter into it.

[Advertisement] Keep all your packages and Docker containers in one place, scan for vulnerabilities, and control who can access different feeds. ProGet installs in minutes and has a powerful free version with a lot of great features that you can upgrade when ready.Learn more.