tags:

views:

112

answers:

1

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!

+3  A: 

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.

  1. 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.
  2. Because 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.
Adam Robinson
Yes I agree, that's what has sparked this question, I tend to remove old VB code wherever I find it!
Stevo3000
I couldn't agree more. "ReDim" and "New Byte(-1)" just look WRONG. To my eye it looks like it's saying ReDim oBytes(-1 to 0), which looks like it should give an array of two elements (which it will in Vb6). Please, please PLEASE can't the world just pretent there was no VB before VB.net? Please?
Binary Worrier
@Binary Worrier - 100% with you on this! It's the reason for most of the VB.NET usability issues!
Stevo3000