Whenever an object is created, it is instantiated in several
ways. The most common way to instantiate an object is using the new
keyword.
Listing 1
DataTable table = new DataTable();
Using some of the design patterns, which we will talk about
in a moment, instantiate objects using the new keyword. However, there
are dynamic ways to create an object, such as the Activator class's
CreateInstance and CreateInstanceFrom methods. These methods have various
overloads. One of the overloads is a generic method that takes the type
to instantiate. Another takes a Type object and instantiates it using this
type. If a more dynamic reference is needed, the method can take an
assembly name and the name of the type to instantiate. Note, on some
overloads the method returns an ObjectHandle and not an object. To get
the object reference, call the Unwrap method. The following is a few
variations.
Listing 2
MyClass classInfo = Activator.CreateInstance<MyClass>();
MyClass classInfo = (MyClass)Activator.CreateInstanceFrom(
"MyComponentLibrary", "MyComponentLibrary.MyClass").Unwrap();
Type type = Type.GetType("MyComponentLibrary.MyClass,MyComponentLibrary");
MyClass classInfo = (MyClass)Activator.CreateInstance(type);
If the object being instantiated does not have a default
parameterless constructor, then there is an overload that takes an object
parameter array, representing the values of the objects defined in the
constructor. The types of these objects have to match the parameter types for
the specific constructor. This approach is more synonymous with using the
ConstructorInfo object, a part of the Reflection API. Using Reflection, a
type can access the constructor through the GetConstructor() or
GetConstructors() methods. This object contains the definition and parameter
types of the constructor, and an object reference can be created using the
Invoke method.
Listing 3
MyClass classInfo = null;
ConstructorInfo constructor = type(MyClass).GetConstructors()[0];
if (constructor != null)
classInfo = (MyClass)constructor.Invoke(new object[] { "Some Name", 1, "Sidney" });
There are varying thoughts about the cost that reflection
has in an application. Some say that using reflection in an application does
have a significant performance hit, while others say that in reality the hit is
negligible and is worth the cost to gain some of the added capabilities that
reflection has in the .NET Framework.