开发者

What is the advised way to make an empty array in VB.NET?

开发者 https://www.devze.com 2022-12-08 23:49 出处:网络
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?

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!


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.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号