6

I was amazed (and horrified) 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

When run, four message boxes pop up 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 structure here that is apparently not supported. The first code example above should be:

Dim test2DArr As String(,) = {{"A", "B"}, {"C", "D"}}

For Each arr As String(,) In test2DArr
  MsgBox(arr(0) & ", " & arr(1))
Next

and should produce two message boxes: "A, B" and "C, D", but the compiler insists that iterating through a 2-d array yields a sequence of strings, not a sequence of arrays of strings.

Am I doing something wrong or is .Net's implementation of 2-D arrays really that flimsy?

1
  • +1 This is absolutely fascinating to me. I set this situation up here if other readers want to experience it for themselves. Commented Aug 24, 2011 at 16:04

1 Answer 1

4

is .Net's implementation of 2-D arrays really that flimsy?

Yes. Multi-dimensional arrays were never really supported in .NET. I’m not sure why they exist at all (as opposed to arrays-of-arrays, i.e. jagged arrays: String()()). In any case, all the support is tailored to the special case of one-dimensional arrays. The framework type for arrays is always the same, regardless of dimensionality, and the interface implementation (in this case of IEnumerable(Of T)) is tailored to this common use case.

This means that the type of the array is always an “array of strings”, and thus it always implements the interface IEnumerable(Of String). This explains why your second code cannot work: in order for it to work, the type of the array would have to be different.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow. That is supremely lame. Your answer, on the other hand, was great. Thank you, and thanks also for hipping me to jagged arrays, which I had never done in .Net. They provide an uglier, but still useful solution to this problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.