Call Function by String Name in Visual Basic .NET

Introduction: This tutorial is on how to run a function using it's reference name as a string in Visual Basic .NET. Built In: Luckily enough, the .NET framework has a built in function which allows an object, string function name, invoke type, and parameters to be called - this function is named 'CallByName'. The function is not an expression and so it must be assigned to an object, although we don't have to use the object afterwards. CallByName Function: The CallByName function takes the following parameters; Example - Class: For my example, I will be using a test game character class with a variable holding the characters name, and a single function to output the characters name. The class will be called 'Character', and it looks like so;
  1. Public Class Character
  2. Dim name As String = String.Empty
  3.  
  4. Public Function outputName()
  5. MsgBox(name)
  6. End Function
  7. End Class
As you can see, the function is named 'outputName', and it does not take any parameters. Let's also create another function called 'changeName' which will take one parameter as a string array. This function will change the name. Why do we use a string array as our functions parameters? That's because if we were wanting to call many different functions from our 'CallByName' method in our first/original class, each one would need a different amount of parameters and so if they all take an array, they can extract their own data within the function itself.
  1. Public Function changeName(ByVal newName As String)
  2. name = newName
  3. End Function
Example - Calling: So first we need to create a new instance of our 'Character' class, I'll call mine 'character'...
  1. Dim character As New Character
Then we simply want to create a new object and set it equal to our 'CallByName' function using the information required.
  1. CStr(CallByName(character, "outputName", Microsoft.VisualBasic.CallType.Method, Nothing))
We can then set up a test environment where it runs the 'outputName' function, followed by changing and then re-outputting the name again; like so...
  1. Dim params As New List(Of String)
  2. params.Add("myNewName")
  3. CStr(CallByName(character, "outputName", Microsoft.VisualBasic.CallType.Method, Nothing))
  4. CStr(CallByName(character, "changeName", Microsoft.VisualBasic.CallType.Method, params))
  5. CStr(CallByName(character, "outputName", Microsoft.VisualBasic.CallType.Method, Nothing))
Finished!

Add new comment