John
John

Reputation: 1338

How do I iterate through variables by name?

If I have the following code:

Private answer1 as boolean = false
Private answer2 as boolean = false
Private answer3 as boolean = false
.
.
Private answer100 as boolean = false

Private Sub check_answers()

     For x As Integer = 0 To 100
       if answer[x] = true then
          ' do something
       else
          ' do something else
       endif

     Next

End Sub

How do I iterate through all of the answer variables by name? the answer[x] option isn't working. Thanks.

Upvotes: 0

Views: 102

Answers (3)

Nizam
Nizam

Reputation: 4699

EDITED

Correcting your code, it would be:

Private answers(100) as boolean
'The array starts from 0

Private Sub check_answers()
   For x As Integer = 0 To 100
      if answers(x) then 
         ' do something
      else
         ' do something else
      endif
   Next
End Sub

The array starts from 0 and the last element is the value used in declaration (for example, answers(100) would have 101 elements - from 0 to 100).

Upvotes: 0

the_lotus
the_lotus

Reputation: 12748

Instead of having 100 variables. Just have a single list.

Private answers As New List(Of Boolean)

Then you can check a single item in a list (not the '()' instead of '[]')

if answers(x) = true then

Also, you could pre-populate 100 items

For x As Integer = 1 To 100
    answers.Add(False)
Next

Upvotes: 2

Kenneth S
Kenneth S

Reputation: 66

The easiest way to do this is to create an array of the values that you want to iterate across:

Dim answer = {answer1, answer2, ...(and so on)} '*** 

You could take a look at http://msdn.microsoft.com/en-us/library/y13tek7e.aspx for more information on how to use arrays in VB.Net.

Beyond this, it is possible to do what you want using a technique called reflection - however I suspect that this might be more complicated than you wish. You can get a good introduction to using reflection in VB.net by reading this article: http://msdn.microsoft.com/en-us/magazine/cc163750.aspx .

Upvotes: 0

Related Questions