Using a ConstructorInfo to create new instance : Constructor « Reflection « C# / CSharp Tutorial






using System;
using System.Reflection;
using System.Globalization;
  class Class1
  {
    DateTime[] dateTimes = new DateTime[10];
    public DateTime this[int index]
    {
      get{ return dateTimes[index]; }
      set{ dateTimes[index] = value;}
    }
    
    
    private DateTime dateOfBirth;
    public DateTime DateOfBirth
    {
        get{ return dateOfBirth; }
        set{ dateOfBirth = value; }
    }
      
    public void Test()
    {
      Console.WriteLine("Test method called");
    }
    
    
    private string field;
    
    public string Property
    { 
      get{ return field; }
      set{ field = value; }
    }
    
  }


    class MainClass{
    
    static void Main(string[] args)
    {
      Type type = Type.GetType("Class1");
      object o = Activator.CreateInstance(type);
      
      type.InvokeMember("Test", BindingFlags.InvokeMethod,null, o, new object[]{});
      
      // Using a ConstructorInfo
      ConstructorInfo constructorInfo = type.GetConstructor(new Type[]{});
        
      o = constructorInfo.Invoke(new object[]{});
      
      type.InvokeMember("Test", BindingFlags.InvokeMethod,null, o, new object[]{});
      
      // Type.InvokeMember
      o = type.InvokeMember("Class1", BindingFlags.CreateInstance, null, null, new object[]{});
      
      type.InvokeMember("Test", BindingFlags.InvokeMethod,null, o, new object[]{});

    }
    }








19.3.Constructor
19.3.1.Get constructor information: Display return type, name and parameters
19.3.2.Find matching constructor
19.3.3.Dynamically invoking constructors
19.3.4.Utilize MyClass without assuming any prior knowledge: invoke constructor
19.3.5.Using a ConstructorInfo to create new instance
19.3.6.Call parent constructor from abstract class
19.3.7.Get the ConstructorInfo object matching the specified binding flags, and displays the signature of the constructor.