Hello. I have a question, is it possible to call the constructor of an object if you don’t know exactly what type it is? Several other classes are inherited from one base class. In the parameters of a certain function, I send an object that is inherited from the parent. In the method there is a check whether the object is null, if so, you need to create an object. I can determine the type of an object, but I have a problem with creating a constructor. Here is an example of the function:

public static void Open(Form form) { if (form==null) form = new Form();//Вместо этого определить тип(Form1, Form2, и т.д.) //и вызвать нужный конструктор ... } 
  • And how do you determine the type? What prevents you from creating objects of the type you need? - Primus Singularis
  • At first, I wanted to solve the problem in a completely different way, in general, it is not even necessary to define the type, it was much easier to use universal types - Max

1 answer 1

Something like that?

 void Main() { OpenForm<Form>(); OpenForm<Form1>(); OpenForm<Form2>(); OpenForm<Form3>(); } class Form1 : Form { } class Form2 : Form { } class Form3 : Form { } void OpenForm<T>() where T:Form, new() { var form = new T(); form.ShowDialog(); } 

But this is only for forms with constructors without parameters.

  • And how will this be better than new Form (), new Form1 (), etc., if the type is known at the compilation stage? - Primus Singularis
  • one
    @PrimusSingularis Why should it be better if the type is known? And where did you get the idea that he is known? I simply answered the question posed, and why does the author need this method - ask the author - tym32167