KnowDotNet NetRefactor

NET Refactor - Refactor Strings

Cleaning up String Concatenation

String contatenation has always been messy and wasteful of resources because strings are immutable.  In other words, once a string is created, it cannot be changed.  Consequently, when you concatenate one string to another, the original string is discarded, to be cleaned up by garbage collection at some time in the future, and a new memory block must be allocated to contain the new string resulting from the concatenation.  Consider what is happening if you are doing this time and time again in your application.

.NET provides a new object called a StringBuilder and you should use it if you are going to concatenate more that two or three strings together.  However, if you are converting from VB6, you had no choice, and many times, if you are like this developer, bad habits are hard to break, and you forget that you have the StringBuilder object.

Refactor Strings is a feature of NET Refactor that will automatically convert a selected block of code, which is concatenatiing strings, to use a StringBuilder.  Consider the following sequence of code, which is creating a dynamic SQL statement (which is a bad practice in itself, but often used by multitudes of developers).   It is not very long, but illustrates the feature.

      Dim sql As String = _
        
"select * "
      sql &= "from table "
      sql &= "where a = '" & cs & "' " & _
            
"and a = '" & b & "' "
      If i = 0 Then
         sql &= "order by test"
         i = 0
      
End If

With NET Refactor, you can select the block of code, click the Refactor Strings menu option and the code shown below will replace the original code.

      Dim sb As New System.Text.StringBuilder()
      
Dim sql As String
      sb.Append("select * ")
      sb.Append(
"from table ")
      sb.Append(
"where a = '" & cs & "' ")
      sb.Append(
"and a = '" & b & "' ")
      
If i = 0 Then
         sb.Append("order by test")
      
End If
      sql = sb.ToString()

The code has been refactored automatically.  It is cleaner.  It uses less resources and runs faster and you can do it with the click of the mouse.

Try NET Refactor Free for 30 days or purchase now by clicking Download or Purchase.

Top of Page

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing