Invoke a Method by Name

Problem

You want to invoke a method or set a property that’s named in a string.

Solution

Use the Type.InvokeMember method.

Discussion

The Type class provides an InvokeMember method that’s similar to the CallByName function in Visual Basic 6. It requires the object; the name of the field, property, or method (as a string); a flag that indicates whether the string corresponds to a field, property, or method; and an array of objects for any required parameters. For example, you can call a method with no arguments using this syntax:

Dim MyObject As New MyClass() Dim TypeInfo As Type = MyObject.GetType() ' Call Refresh() on MyObject. Dim Args() As Object = {} TypeInfo.InvokeMember("Refresh", BindingFlags.Public Or _ BindingFlags.InvokeMethod, ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.