What is the best way to take an array in VB.NET which can either be Nothing or initialised and give it a length of zero?
The three options I can think of are:
ReDim oBytes(-1)
oBytes = New Byte(-1) {}
oBytes = New Byte() {}
The first example is what most of the developers in my company (we used to do VB 6) have always used. I personaly prefer the third example as it is the easiest to understand what is happening.
So what are the positives and negative to each approach (option 2 and 3 are very similar I know)?
EDIT
So does anyone know of a reason to avoid ReDim
other that because it is a holdover from the VB days?
Not that I won't accept that as the answer if that is all anyone has!
This is the fastest way to empty an array: a = []; This code assigned the array a to a new empty array. It works perfectly if you do not have any references to the original array.
In visual basic, Arrays can be declared by specifying the type of elements followed by the brackets () like as shown below. Dim array_name As [Data_Type](); Here, array_name represents the name of an array and Data_type will represent the data type of elements to store in an array.
An empty array will have 0 elements inside of it.
All arrays must be zero-indexed. In Microsoft Visual Basic 6.0, you can define arrays with the lower bounds and upper bounds set to any integer. In Microsoft Visual Basic . NET, the lower bound of every array dimension is zero (0).
I recommend: oBytes = New Byte() {}
You should try to avoid "classic VB-isms" like Redim
, and other holdovers from the classic VB days. I would recommend the third option.
Edit
To provide some more information about why to avoid it, see this MSDN page. While the page doesn't specifically advise against it, you can see that Redim
suffers from shortcomings (and potential for confusion) that the other syntax does not.
Redim
can only be used on existing arrays. Even so, it is semantically equivalent to declaring a new
array. Redim
releases the old array and creates a new one (so it isn't as if Redim
has the ability to "tack on" or "chop off" elements). Additionally, it is destructive unless the Preserve
keyword is used, even though there is no visual indication that an assignment is taking place.Redim
cannot create an array (but can only work on existing arrays), it can only be used within a procedure; at the class level you're forced to use the New Byte() {}
method, leaving you with two visually distinct patterns for assigning new arrays, even though they're semantically identical.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With