views:

1564

answers:

4
+1  Q: 

VB.NET Dim vs. New

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


Dim byteArray(20) as Byte

and


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

Edit - Corrected the ReDim. Should be a Dim.

+1  A: 

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

Spencer Ruport
+1  A: 

It's the same thing.

Always more than 1 way to skin a cat.

Eppz
+2  A: 

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.

Surely it's 21 bytes?
RobS
It is, as the syntax for Dim/Redim is to specify the last index, rather than the count
Rowland Shaw
+1  A: 

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...

Hans Passant