Array Declaration Syntax

  • Thread starter Thread starter Jerry Camel
  • Start date Start date
J

Jerry Camel

VB seems to accept both versions of this declaration... Are they
equivalent?

Dim Bytes() As Byte = New Byte(Part1.Length + Part2.Length) {} 'Without the
braces, vb complains that Byte has no constructor.
Dim Bytes(Part1.Length + Part2.Length) As Byte

Thanks,
Jerry
 
Jerry,
In addition to Mattias's comments.

Just be warned, that your Bytes array will be "off by one" then the total of
your Part1 & Part2.

Remember that when you define an Array the Upper bound is given, not length.
The lower bound is always Zero.

If you want Bytes to contain the same number of elements as Part1 & Part2
you need to subtract one from the total of their lengths...

Something like:
Dim Bytes(Part1.Length + Part2.Length -1 ) As Byte

For example:
Dim part1(10), part2(10) As Byte
Dim Bytes(Part1.Length + Part2.Length) As Byte

Part1 & Part2 will each have 11 elements, while Bytes will have 23 elements.

Hope this helps
Jay
 
Thank you gentlemen...

Regarding the size issue (And I'm talking about array sizes...) This
question came up whe I was converting some code from C# to VB .NET. Is
there any reason you wouldn't run into the same issue in C#? (I'm just
wondering why the guy that wrote the C# didn't account for this.)

Thanks.

Jerry
 
Jerry,
Is there any reason you wouldn't run into the same issue in C#?

Yes, in C# (and other C style languages) the number inside the square
brackets indicate the array length. So new int[10] gives you an array
of 10 elements, index 0-9.

In VB it works like Jay said, the number you provide specifies the
upper bound. So New Integer(10) {} has 11 elements, index 0-10.



Mattias
 
Back
Top