3.12. Instantiate an Object Using Reflection

Problem

You need to instantiate an object at runtime using reflection.

Solution

Obtain a Type object representing the type of object you want to instantiate, call its GetConstructor method to obtain a System.Reflection.ConstructorInfo object representing the constructor you want to use, and execute the ConstructorInfo.Invoke method.

How It Works

The first step in creating an object using reflection is to obtain a Type object that represents the type you want to instantiate. (See recipe 3-10 for details.) Once you have a Type instance, call its GetConstructor method to obtain a ConstructorInfo representing one of the type's constructors. The most commonly used overload of the GetConstructor method ...

Get Visual Basic 2008 Recipes: A Problem-Solution Approach 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.