Cant assign array values ! ? ! ?

  • Thread starter Thread starter Chris Wertman
  • Start date Start date
C

Chris Wertman

I am so lost on this one.

Dim Ary as Integer = New Integer(4) {0,1,2,3}

FAILS with the error:
Array initializer has 1 too few elements.

So I try
Dim Ary as Integer = New Integer(3) {0,1,2,3}
Since arrays start at 0 (I am thinking)

and I get this error:
Value of type '1-dimensional array of Integer' cannot be converted to 'Integer'.

I can friggin assign values to the array AT ALL ?

What is wrong with this ?

So I guess the question is why dosent this work ?

How can I dimension and assign values ?

Chris
 
If you want an array, you need to declare an array...
( note the () after the Ary )
Dim Ary() As Integer = New Integer(3) {0, 1, 2, 3}

For i As Integer = 0 To Ary.Length - 1

Trace.WriteLine(Ary(i).ToString())

Next
 
Yes, and when initializing, you don't have to specify the number of elements
in the array, thus
Dim Ary() As Integer = New Integer() {0, 1, 2, 3}
will work as well.
 
That's what I said, "when initializing, you don't have to specify ...",
read my message.
 
<you don't have to specify the number of elements in the array>

EXCEPT when you are not specifying the values at the time of creating the
array. In such a case you DO have specify the number of elements ahead of
time. Just something to keep in mind.

public sub test()
dim ary(0) as integer
ary(0) = 1

'to add another element--but this will overwrite previous elements
redim ary(1)
ary(1)=2

msgbox(ary(0).tostring +vbcrlf + ary(0).tostring) '<-this will display 0
even though you previously set it to 1

'set it back to 1
ary(0) = 1

'here we add another element while leaving the previous elements untouched.
redim preserve ary(2)
ary(2) = 3

msgbox(ary(0).tostring + vbcrlf + ary(1).tostring + vbcrlf +
ary(2).tostring)
end sub
 
* (e-mail address removed) (Chris Wertman) scripsit:
I am so lost on this one.

Dim Ary as Integer = New Integer(4) {0,1,2,3}

FAILS with the error:
Array initializer has 1 too few elements.

So I try
Dim Ary as Integer = New Integer(3) {0,1,2,3}
Since arrays start at 0 (I am thinking)

and I get this error:
Value of type '1-dimensional array of Integer' cannot be converted to 'Integer'.

I can friggin assign values to the array AT ALL ?

What is wrong with this ?

\\\
Dim i() As Integer = {1, 2, 3}
///

- or -

\\\
Dim i As Integer() = {1, 2, 3}
///
 
I DID read your message and I didn't say you were wrong. The OP sounded
like he was new to arrays and I thought he might take
"you don't have to specify the number of elements in the array when
initializing, you don't have to specify" as meaning that he didn't need to
specify the number of arrays anymore.

I meant no offense to anyone and like I said, I wasn't trying to say that
you were wrong.
 
Back
Top