The reason for doing that is to try and explain the theory of this bug here.
1. We have defined a global variable that is a stringbuilder called
sb. If we append anything to it, we should get back what was there initially and the new additions, right?
2. Above we have 2 subs, one named Join and the other Join1. The stringbuilder variable in Join is named
sb and the one in Join1 named
sbx.
Now, if one would run.
Log(Join(",", Array("b4x"," is"," cool")))
it will print this only.
Right? Join1 will also do the same
3. Now...
We have defined a global variable named
sb as stringbuilder in our class
Private sb As StringBuilder
4. When the class is initialized,
we add some content to this sb variable
sb.Initialize
sb.Append("Mashy...").Append(CRLF)
sb.Append("Mashy Again...").Append(CRLF)
5. In the main code, we define and initialize the class.
Dim cls As SBClass
cls.Initialize
If you would change sb to Public in the class and execute log(cls.sb.ToString) it will show..
Mashy...
Mashy Again...
Now if, we append anything to this
global sb stringbuilder variable, it should add to the already existing content.
To test our theory here, we will create a list of items and then join them using the stringbuilder methodology. To do this we will create a subroutine to join items in a list using a stringbuilder class. These are the two subs above one with sb and sbx as stringbuilders.
6. Running Join which gives wrong output (using sb local variable)
Sub Create
Dim xitems As String = Join(",",items)
sb.Append(xitems)
Log(sb.ToString)
End Sub
Result
a,b,ca,b,c
7. Running Join1 which gives correct output (using sbx local variable)
Sub Create
Dim xitems As String = Join1(",",items)
sb.Append(xitems)
Log(sb.ToString)
End Sub
Result
Mashy...
Mashy Again...
a,b,c
The only difference between the two subroutines is the variable name between sb and sbx. With Join, all the contents of the global sb are overwritten. With sbx, the correct code execution happens. Thing
Dim sb as stringBuilder inside Join is supposed to be having a local scope to that sub ONLY, however it's affecting the global variable scope. Thus this thread. I hope you understand.
Ta!