Find matching 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() { 
    Type t = typeof(MyClass); 
    int x; 

    // Find matching constructor. 
    ConstructorInfo[] ci = t.GetConstructors(); 
 
    for(x=0; x < ci.Length; x++) { 
      ParameterInfo[] pi =  ci[x].GetParameters(); 
      if(pi.Length == 2) break; 
    } 
 
    if(x == ci.Length) { 
      Console.WriteLine("No matching constructor found."); 
      return; 
    } 
    else 
      Console.WriteLine("Two-parameter constructor found.\n"); 
 
  } 
}
Two-parameter constructor found.








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.