Hi again
i have a strange issue today. Sample code is at the below of the post. The code that i have pointed out is too strange. According to my knowledge using return statement the functions return values as byval and copies the value to the stack. Also how can my class can reach outscope elements and change them. Take a look at to the code below. How this could be?

code Code:
  1. Public Class Form1
  2.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  3.         Dim b As New ByteClass
  4.         Dim sumArray As Long = 0
  5.         Dim ByteArray As Byte() = {}
  6.         Dim idx As Integer = 0
  7.         ByteArray = b.GetArray
  8.         sumArray = SumByteArray(ByteArray)
  9.         Do
  10.             idx += 1
  11.             If sumArray <> SumByteArray(ByteArray) Then Exit Do
  12.             Debug.Print("Not changed yet" + "" + Str(idx))
  13.         Loop
  14.         MsgBox("The ByteArray has changed???")
  15.     End Sub
  16.  
  17.     Public Function SumByteArray(ByVal pByteArray As Byte()) As Long
  18.         'This function return the sum value of the ByteArray
  19.         Dim retval As Long = 0
  20.         For i As Integer = 0 To pByteArray.Length - 1
  21.             retval = retval + pByteArray(i)
  22.         Next
  23.         Return retval
  24.     End Function
  25. End Class
  26. Class ByteClass
  27.     Dim ByteArray As Byte() = {}
  28.     Dim Foo As System.Threading.Thread
  29.     Sub New()
  30.         ByteArray = New Byte(4096) {}
  31.         Foo = New System.Threading.Thread(AddressOf ThreadWork)
  32.         Foo.Start()
  33.     End Sub
  34.     Public Function GetArray() As Byte()
  35.         Return ByteArray
  36.     End Function
  37.     Sub ThreadWork()
  38.         'Generate a random mutation on bytestream
  39.         Dim r1 As New Random
  40.         Dim r2 As New Random
  41.         Dim idx As Integer
  42.         Dim v As Integer = 0
  43.         Do
  44.             v = r1.Next(0, 255 + 1)
  45.             idx = r2.Next(0, 4096 + 1)
  46.             ByteArray(idx) = v
  47.             Application.DoEvents()
  48.         Loop
  49.     End Sub
  50. End Class