I want to know how to create an object of a class with the help of reflection, with which a constructor is clearly registered. Suppose there is a class Student:

class Student { private int _temp = 10; private string name = "Vasya"; } 

In this case, the use of reflection when creating an instance is as follows:

 class Program { static void Main(string[] args) { Type type = typeof(Student); ConstructorInfo info = type.GetConstructor(new Type[] { }); object student = info.Invoke(new object[] { }); } } 

But if a clearly defined constructor appears in my student, for example:

 class Student { private int temp; private string name; public Student(int temp, string name) { this.temp = temp; this.name = name; } } 

how exactly should I pass the parameters in the calling part of the program? Namely here:

  ConstructorInfo info = type.GetConstructor(new Type[] { }); object student = info.Invoke(new object[] { }); 

    2 answers 2

    You need to get this constructor:

     ConstructorInfo info = type.GetConstructor(new Type[] { typeof(int), typeof(string) }); 

    And pass the parameters to it:

     object student = info.Invoke(new object[] { 20, "Petya" }); 

      Why not just

       var student = (Student)Activator.CreateInstance(typeof(Student), 1, "Vasya");