Is it possible to assemble a function address from strings?

Stuart Coutts 61 Reputation points
2021-04-10T15:53:48.453+00:00

I am trying to simplify some code and make it a bit more dynamic.

Currently the code looks like this (simplified to aid in this question)...

If x = "_One" Then
    Module_One.Main()
Elseif x = "_Two"
    Module_Two.Main()
Elseif x = "_Three"
    Module_Three.Main()
...
Elseif x = <"_n">
    Module<_n>.Main()
End If

...where depending on x as string, a function called "Main" in a module called Module<x> is then called.

Ideally I would like the code to function like this (i'm riffing on this code as I don't actually know if its even possible)...

Dim ModuleName as Module = "Module" & x
ModuleName.Main()

The closest example I can think of would be like when one builds a cell address from cell values, using indirect, in excel but instead of a cell address its a function address in different modules in vb.

Developer technologies | VB
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2021-04-10T17:33:33.81+00:00

    Check this code:

    Dim x As String = "_Two"
    Dim ModuleName As String = "Module" & x
    
    Dim type As Type = Assembly.GetExecutingAssembly.GetTypes.First(Function(t) t.Name = ModuleName)
    Dim [sub] As MethodInfo = type.GetMethod("Main", BindingFlags.Static Or BindingFlags.Public Or BindingFlags.NonPublic)
    
    [sub].Invoke(Nothing, Nothing)
    

    It assumes that the module is:

    Module Module_Two
    
        Public Sub Main()
            . . .
        End Sub
    
    End Module
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Stuart Coutts 61 Reputation points
    2021-04-10T18:21:26.26+00:00

    That is incredible.

    Three lines of code ive never used or even seen before.
    Not sure how it works but it works exactly as I wanted.

    I'm gona have to deconstruct that and learn exactly whats going on.

    Cannot thank you enough.

    You're a star!

    Thanks again!

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.