KnightsOfTheRoun
KnightsOfTheRoun

Reputation: 155

Reference Variable names as strings

I am trying to reference the name of a variable as a string. I have a list of global variables

Public gvHeight As String = Blank
Public gvWeight As String = Blank
Public gvAge As String = Blank

I need to reference the name of the variables for an external API call. I am trying to avoid specific code per variable, instead allow me to add a new variable and everything reference correctly. I already have the rest of the code to deal with the name as a string.

example:

public Height as string
public weight as string
public age as string

[elsewhere in code]
for each var as string in {public variables}
   CallToAPI(var.name) 'needs to send "height" "weight" or "age" but there are a lot so hardcoding is not a good solution

edited for example

Upvotes: 2

Views: 705

Answers (2)

ElektroStudios
ElektroStudios

Reputation: 20474

You need to find the public fields through Reflection.

Having an example dll compiled from this source-code:

Public Class Class1

    Public Field1 As String = "value 1"
    Public Field2 As String = "value 2"
    Public Field3 As Integer

End Class

Then you could do this:

' The library path.
Dim libpath As String = "...\ClassLibrary1.dll"

' The assembly.
Dim ass As Assembly = Assembly.LoadFile(libpath)

' The Class1 type. (full namespace is required)
Dim t As Type = ass.GetType("ClassLibrary1.Class1", throwOnError:=True)

' The public String fields in Class1.
Dim strFields As FieldInfo() =
    (From f As FieldInfo In t.GetFields(BindingFlags.Instance Or BindingFlags.Public)
     Where f.FieldType Is GetType(String)
    ).ToArray

' A simple iteration over the fields to print their names.
For Each field As FieldInfo In strFields
    Console.WriteLine(field.Name)
Next strField 

Upvotes: 1

Martin Verjans
Martin Verjans

Reputation: 4806

If all your variables are of the same type (here strings), you can use a Dictionary...

Public MyModule
  Private myVars As Dictionary(Of String, String)

  Public Function CallToAPI(VarName As String) As String
      If myVars.ContainsKey(VarName) Then
          Return myVars(VarName)
      End If
      Return ""
  End Function
End Module

And somewhere else in your external code

Module TestModule

Public Sub Test()
    Dim myVar = MyModule.CallToAPI("test")

End Sub

End Module

Now if your variables aren't the same, then you must use Reflection... and that's where the fun begins...

Upvotes: 0

Related Questions