2

I declared an array of strings and initialized every element to "5". But when I debug with a breakpoint after the For-Each, all my array members have Nothing in them. I'm on Visual Studio 2010. Help please?

Dim words(999) As String

For Each word As String In words
    word = "5"
Next
1
  • This initializes nothing. The iterator returns a temporary string that contains the value of the item in the array. Since you've put nothing in there, there's nothing to get back. You might want to read Arrays in VB.Net here to help you get started. I removed the extraneous tags like microsoft, visual, and basic, as VB.NET automatically means those things. Visual Studio is pretty much implied as well. Commented Oct 5, 2011 at 23:17

2 Answers 2

3

What you have there is good for reading array's, but not for writing them. Your code translates to:

Create words array with 1000 elements
For each index in the array
    word = words(index)
    word = "5"
Next index

At no point does it put the word back into the array. The code is missing:

    ...
    words(index) = word
Next index

What you need to do is:

Dim words(999) As String

For index As Integer = 0 to words.Length - 1
    words(index) = "5"
Next

Edit: In response to the comment below.

Once you've initialised the array, you can use a For/Each loop to read the elements.

For Each word As String in words
    Console.WriteLine(word)
Next

This is the same as:

For index As Integer = 0 To words.Length - 1
    Console.WriteLine(words(index))
Next
Sign up to request clarification or add additional context in comments.

2 Comments

Does this mean I can't/shouldn't use for-each for arrays?
You can't use For/Each for initialising arrays. For/Each is only useful for reading arrays. See my edited answer.
1

You can also do this:

Dim Words() As String = Enumerable.Repeat("5", 1000).ToArray()

Comments

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.