Ali_R4v3n
Ali_R4v3n

Reputation: 377

looping through variables during runtime

is there a way to loop through a set of defined variables during runtime without having to write a new line of code to handle each variable for example the following code of a console application:

Module Module1

    Sub Main()
        Dim a!, b#, c%, d&, s$

        Console.WriteLine("a " & VarType(a).ToString)
        Console.WriteLine("b " & VarType(b).ToString)
        Console.WriteLine("c " & VarType(c).ToString)
        Console.WriteLine("d " & VarType(d).ToString)
        Console.WriteLine("s " & VarType(s).ToString)
        Console.ReadLine()
    End Sub
End Module

a dummy code would be something like this :

for each Var in DefinedVariables 
'Do Something To the variable
next 

Upvotes: 1

Views: 79

Answers (2)

Bradley Uffner
Bradley Uffner

Reputation: 16991

You can use MethodBody.LocalVariables to retrieve local variables declared within a method body as a list of LocalVariableInfo instances. Unfortunately you only have access to them via index, as the name is not stored. You basically get the variable type, the ordinal it was declared at, and whether or not it is pinned. Optimization may even reorder variables or completely eliminate them.

Dim mi As MethodInfo =  GetType(Example).GetMethod("MethodBodyExample")
Dim mb As MethodBody = mi.GetMethodBody()
Console.WriteLine(vbCrLf & "Method: {0}", mi)

' Display the general information included in the 
' MethodBody object.
Console.WriteLine("    Local variables are initialized: {0}",  mb.InitLocals)
Console.WriteLine("    Maximum number of items on the operand stack: {0}",   mb.MaxStackSize)

' Display information about the local variables in the
' method body.
Console.WriteLine()
For Each lvi As LocalVariableInfo In mb.LocalVariables
    Console.WriteLine("Local variable: {0}", lvi)
Next

Upvotes: 1

p3tch
p3tch

Reputation: 1495

As I said in the comments, use a collection. For example

    Dim letters As New List(Of String) From {"a", "b", "c", "d"}

    For Each letter In letters
        Console.WriteLine(letter)
    Next

Edit:

    Dim a As String = "a"
    Dim b As String = "b"
    Dim c As String = "c"
    Dim d As String = "d"
    Dim e As Integer = 123

    Dim variables As New List(Of Object) From {a, b, c, d, e}

    For Each value In variables
        Console.WriteLine(value.ToString)
    Next

Upvotes: 0

Related Questions