Iterate through 2nd array in VB.Net

I was amazed (and terrified) that the following code works in Vb.Net

Dim test2DArr As String(,) = {{"A", "B"}, {"C", "D"}} For Each s As String In test2DArr MsgBox(s) Next 

At startup, four message boxes appear, showing "A", "B", "C", and then "D".

In other words, it has exactly the same behavior as:

 Dim test1DArr As String() = {"A", "B", "C", "D"} For Each s As String In test1DArr MsgBox(s) Next 

Can someone explain this "feature"? I need to impose some kind of structure here, which, apparently, is not supported. First code example above:

 Dim test2DArr As String(,) = {{"A", "B"}, {"C", "D"}} For Each arr As String(,) In test2DArr MsgBox(arr(0) & ", " & arr(1)) Next 

and should create two message windows: "A, B" and "C, D", but the compiler insists that iterating through the 2nd array gives a sequence of strings, not a sequence of arrays of strings.

Am I doing something wrong or is this .Net implementation of two-dimensional arrays really so flimsy?

+4
source share
1 answer

.Net implementation of two-dimensional arrays really so flimsy?

Yes. Multidimensional arrays were never supported in .NET. I'm not sure why they exist at all (unlike arrays of arrays, i.e. Arrays with notches: String()() ). In any case, all support is adapted to the special case of one-dimensional arrays. The type of structure for arrays is always the same, regardless of the dimension, and the implementation of the interface (in this case IEnumerable(Of T) ) is adapted to this usual use case.

This means that the type of the array is always a "string array" and therefore it always implements the IEnumerable(Of String) interface. This explains why your second code cannot work: in order for it to work, the type of the array had to be different.

+2
source

All Articles