Calling a method by its name
Calling a method by its name <URL:http://dotnet.mvps.org/dotnet/faqs/?id=callbyname&lang=en> ---------------------------------------------------------------------------- Calling a method by its name There are different ways to call methods only by a string that contains their name. The simplest way is to use Visual Basic .NET's 'CallByName' method. The listing below shows some samples of method calls using this method: \\\ Dim mm As New CallByNameDemo() CallByName(mm, "ShowMessage", CallType.Method) CallByName( _ mm, _ "PrintTexts", _ CallType.Method, _ New String(2) {"Text 1", "Text 2", "Text 3"}, _ 2 _ ) CallByName(mm, "SampleProperty", CallType.Set, "MyValue") Console.WriteLine( _ "MakeDouble(""Hello"") returns ""{0}""", _ CallByName(mm, "MakeDouble", CallType.Method, "Hello") _ ) . . . Public Class CallByNameDemo Public Sub ShowMessage() Console.WriteLine("This is a message.") End Sub Public Function PrintTexts( _ ByVal Texts() As String, _ ByVal Times As Integer _ ) As Boolean For Times = 1 To Times For i As Integer = 0 To Texts.Length - 1 Console.WriteLine(Texts(i)) Next i Next Times End Function Public WriteOnly Property SampleProperty() As String Set(ByVal Value As String) Console.WriteLine( _ "'SampleProperty' was set to ""{0}"".", _ Value _ ) End Set End Property Public Function MakeDouble(ByVal Text As String) As String Return Text & Text End Function End Class /// An alternative, more low-level solution is based on reflection, which is provided by the .NET Framework. 'Type.InvokeMember' can be used to invoke a method on an object. The documentation of this method contains some samples on how to use it to access fields, constructors, methods, and properties: .NET Framework Class Library -- 'Type.InvokeMember' Method <URL:http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemTypeClassInvokeMemberTopic.asp>