Utilize MyClass without assuming any prior knowledge: invoke constructor : Constructor « Reflection « C# / CSharp Tutorial






using System; 
using System.Reflection; 

class MyClass { 
  public MyClass(int i) { 
    Console.WriteLine("Constructing MyClass(int). "); 
  } 
 
  public MyClass(int i, int j) { 
    Console.WriteLine("Constructing MyClass(int, int). "); 
  } 
 
  public int sum() { 
    return 0; 
  } 
 
  public bool isBetween(int i) { 
    return false; 
  } 
 
  public void set(int a, int b) { 
    Console.Write("Inside set(int, int). "); 
  } 
 
  public void set(double a, double b) { 
    Console.Write("Inside set(double, double). "); 
  } 
 
  public void show() { 
    Console.WriteLine("Values"); 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    Assembly asm = Assembly.LoadFrom("main.exe"); 
 
    Type[] alltypes = asm.GetTypes(); 
 
    Type t = alltypes[0]; // use first class found 
 
    Console.WriteLine("Using: " + t.Name); 
 
    ConstructorInfo[] ci = t.GetConstructors(); 
 
    // Use first constructor found. 
    ParameterInfo[] cpi = ci[0].GetParameters(); 
    object reflectOb; 
 
    if(cpi.Length > 0) { 
      object[] consargs = new object[cpi.Length]; 
 
      // initialize args 
      for(int n=0; n < cpi.Length; n++) 
        consargs[n] = 10 + n * 20; 
 
      // construct the object 
      reflectOb = ci[0].Invoke(consargs); 
    } else 
      reflectOb = ci[0].Invoke(null); 
     
  } 
}
Using: MyClass
Constructing MyClass(int).








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.