Question

What are the differences between the following constructs? Why prefer one over the other?

Number one:

Dim byteArray(20) as Byte

Number two:

Dim byteArray() as Byte = new Byte(20) {}

Any help would be appreciated.

Thank you.

Edit - I corrected some code. "ReDim" should be "Dim".

Was it helpful?

Solution

They both allocate 20 bytes on the managed heap.

They both set the identifier 'byteArray' to point to those bytes.

The statement with the "new" operator (clause) allows initialization of the array elements.


Dim byteArray() as Byte = new Byte(20) { 1, 2, 3, 4, 5, 6, ... }

Incidentally, to allocate an array with no elements specifiy a size of -1 for one of the dimensions. This is useful if you need to access properties like length without throwing an error.

OTHER TIPS

It's the same thing.

Always more than 1 way to skin a cat.

Yup, the same. The 2nd statement is one to avoid, few would guess that it actually creates an array with 21 elements. Not that it is that obvious from the 1st statement either...

Both are the same.

Dim byteArray(20) as Byte will create an array with 21 elements

Dim byteArray() as Byte = new Byte(20) {} will create an array with 20 element

There's no difference. Redim is carryover syntax that vb 6 developers are familiar with.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top