Instantiate a Type by Name

Problem

You want to create an instance of an object that’s named in a string.

Solution

Use the Assembly.CreateInstance method or the Activator.CreateInstance method.

Discussion

Both the System.Reflection.Assembly and the System.Activator classes provide a CreateInstance method. This recipe uses the Assembly class, and recipe Invoke a Method by Name features an example with the Activator class.

To use CreateInstance, you supply a fully qualified type name. The CreateInstance method searches the assembly for the corresponding type, and then it creates and returns a new instance of the object (or a null reference if the object can’t be found). You can also use overloaded versions of CreateInstance to supply constructor arguments ...

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.