Creating an object instance from a System.Type

Posted: (EET/GMT+2)

 

Wouldn't it be convenient if you could dynamically create object instances given an object type? In C#, we don't have class references like Delphi would, but there's an easy remedy.

Take a look at this piece of code:

private object UniversalClassCreator(System.Type typeToCreate)
{
  System.Reflection.ConstructorInfo ci;
  ci = typeToCreate.GetConstructor(System.Type.EmptyTypes);
  object newObj = ci.Invoke(null);
  return newObj;
}

Okay, that was easy. But do you want to make things still easier? This is as simple as it can possibly get:

object newObj = System.Activator.CreateInstance(typeToCreate);