tmighty tmighty - 6 months ago 26
Vb.net Question

Copy byte array in VB.NET

I am retrieving a byte blob from an SQLite database/record set. I am not experienced with garbage collection yet.

When I say:

Dim bt() As Byte
bt = r.fields("mybyteblob").value


... is that okay or unsafe?

I would like to make a copy of the byte array in the record set field, and I am not sure if I am simply referencing the byte array here instead of copying it.

Answer

In your code you are only referencing the byte array.
If you want to copy it you need

Dim bt() As Byte 
if r.fields("mybyteblob").Value Is not Nothing then 
    dim lenArray = r.fields("mybyteblob").Length
    bt = new Byte(lenArray)
    Array.Copy(r.fields("mybyteblob").value, bt, lenArray)
end if

There is another alternative.
The Buffer class is faster than Array and more appropriate because you are using a byte array

Dim bt() As Byte 
if r.fields("mybyteblob").Value Is not Nothing then 
    dim lenArray = r.fields("mybyteblob").Length
    bt = new Byte(lenArray)
    Buffer.BlockCopy(r.fields("mybyteblob").value, 0, bt, 0, lenArray)
end if

Here a good question on the two methods

Comments