I have a couple of doubts regarding the declaration and initialization of arrays.
Private mat()() As Integer
Private mat2(,) As Integer
Public Sub Prueba()
ReDim mat2(2, 4)
ReDim mat((4)()) //Error
mat = New Integer(1)() //Error
mat = New Integer(1)() {}
mat2 = New Integer(4, 2) //Error
mat2 = New Integer(4, 2) {}
End Sub
Basically I would like to know why those 3 give an error. Why can't I use ReDim on an irregular array? I suppose the 2 and 3 errors are the same, why don't they throw an error when I use the {} and what meaning do the keys themselves have? I saw in some code that they sometimes use {} in variables and I don't understand their usefulness in this regard. In functions or procedures can be used?
If possible. It's just that you're not doing it the right way. Should be:
Simply because the syntax for creating an array using
New
always requires that you include the{}
. They cannot be skipped.I agree that, at first glance, it's hard to understand why the syntax forces you to include them
{}
to allocate a multi-dimensional array or an array of an array. But it is better understood if we consider the most common case, a normal arrangement.For example, let's say you have a simple class defined like this (note the constructor that accepts a numeric value):
So the question is, if assigning an array with
New
does not require the{}
, how should the following statement be interpreted?Am I trying to instantiate
MiClase
using the constructor that accepts a numeric value? Or am I trying to allocate a new array ofMiClase
? It is ambiguous.It is precisely to avoid this type of ambiguity that the VB.NET syntax requires
{}
when assigning a new array with theNew
.The
{}
not only serves to make it clear that you're assigning an array, as I explained above, but it's also where you can optionally assign the initial values for the array.For example:
... allocates an array of
Integer
with 2 elements. And since you don't specify any initial value, the 2 elements are set to zero, the default value for aInteger
.But, if instead, you modify the statement as follows:
... also assigns an array of
Integer
with 2 elements. But this time, the first element is initialized to10
, and the second to20
.The same principle can be used with more complex arrays to initialize their values.
For more information: Arrays in Visual Basic .