run a sub/function by using a string containing its name

  • Thread starter Thread starter Li Pang
  • Start date Start date
L

Li Pang

Hi,

I'd like to know how to call a sub/function bu using a
string containing its name, as an example as follow:

Sub Main()
Dim name As String = "TestMe()"
' need help here

End Sub

Public Sub TestMe()
MsgBox("Hello")
End Sub

Thanks in advance
 
Hi Li Pang,

Have a look at "Delegates".... a new technology for VB.NET. That should
solve your problem.

Regards,
Jan
 
Li Pang said:
Hi,

I'd like to know how to call a sub/function bu using a
string containing its name, as an example as follow:

Sub Main()
Dim name As String = "TestMe()"
' need help here

End Sub

Public Sub TestMe()
MsgBox("Hello")
End Sub

Thanks in advance

What happens if the procedure name does not exist? The application will
crash because the compiler can't find this error.

If you really need it, you can use CallByName (shared member of
Microsoft.VisualBasic.Interaction).
 
Thanks Jan,

I have already used the Delagate. I have two classes,
class A calls class B who does some asynchrous staff
there, at the end, the callback must run the function in
class A. So, class A passes the name of function to class
B, then class B uses this name to run class A's function.

Any suggestion?

regards
 
Hi Armin,

Thanks for your information. To avoid the errors, is that
possible to use some methods to check if the functions
exist before call them?

regards
 
Li,
Look at the classes in the System.Reflection namespace. Which is what the
CallByName method is built-on.

You can use System.Reflection to get a list of methods for an object, given
this list you can verify that the name exists.

If the name is known at compile time I would recommend using a Delegate as
Jan suggested, if you are reading the name from a source external to your
program, then you will need to use CallByName along with the
System.Reflection namespace to call the method.

Of course reading the name of the function to call from an external source
opens a back door into your program allowing functions that should not be
called to be called!

I do not have a specific example of Reflection to verify the name for you.

Hope this helps
Jay
 
Li Pang said:
Hi Armin,

Thanks for your information. To avoid the errors, is that
possible to use some methods to check if the functions
exist before call them?

What would you do if it is not there but you need it?

You could put the code in a try-catch block to catch the exception.
 
* "Li Pang said:
Thanks for your information. To avoid the errors, is that
possible to use some methods to check if the functions
exist before call them?

You can use Reflection to get the methods of a class. Have a look at the
'GetMethod' method of the 'Type' class.
 
use the "callbyname" method and no this is not a joke it is really that simple

regards

Michel Posseth
 
Back
Top