Mega Code Archive

 
Categories / C# Book / 09 Reflection
 

0620 Instantiating Types

There are two ways to dynamically instantiate an object from its type: Call Activator.CreateInstance method Call Invoke on a ConstructorInfo object obtained from a Type Activator.CreateInstance accepts a Type and optional arguments that get passed to the constructor: using System; using System.Reflection; using System.Collections.Generic; class MainClass { static void Main() { int i = (int)Activator.CreateInstance(typeof(int)); DateTime dt = (DateTime)Activator.CreateInstance(typeof(DateTime),2000, 1, 1); } }