Why null return on getting a class constructor?

 class myClass { public int a { get; set; } public int b { get; set; } public myClass() { a = 0; b = 0; } } private void Form1_Load(object sender, EventArgs e) { Type t = typeof(myClass).GetType(); ConstructorInfo constr = t.GetConstructor(new[] { t }); } 

But when you access GetConstructors everything returns normally.

  • 3
    because in the class myClass there is no constructor that takes as an argument an object of the class myClass - Grundy
  • class myClass {public int a {get; set; } public int b {get; set; } public myClass (int a) {a = 2; b = 2; }} private void Form1_Load (object sender, EventArgs e) {Type t = typeof (myClass) .GetType (); ConstructorInfo constr = t.GetConstructor (new [] {typeof (int)}); } - Evgeny Smelov
  • we will redo it so that it will accept int and we will search on intu ... but the result is the same @Grundy - Evgeny Smelov
  • What does the code in the comment mean? - Grundy
  • I changed @Grundy so that the constructor accepts an int. - Evgeny Smelov

2 answers 2

 var type = typeof(myClass); var constructor = type.GetConstructor(Type.EmptyTypes); 

Type getting

To obtain a type at compile time, it is sufficient to use the typeof operator. The typeof operator takes a type name as a parameter. To get the type at runtime, the Object.GetType() method, which returns a Type for an existing object:

 var myClassInstance = new myClass(); var type = myClassInstance.GetType(); 

Sharing them does not make sense.

Getting a constructor without parameters

The Type.GetConstructor(Type[]) method searches for a constructor whose parameters correspond to the types contained in the array passed to the method. Since you want to find a constructor without parameters, you should use the value of the Type.EmptyTypes field.

  • Try to write more detailed answers - Grundy
  • It is worth adding that typeof is applied to types, and GetType to objects. - Grundy

You do not have a constructor with a parameter; you must pass Type.EmptyTypes the Type.GetConstructor (Type []) method . And it is not clear why you take type from typeof (myClass) .GetType ()?

 class myClass { public int a { get; set; } public int b { get; set; } public myClass() { a = 0; b = 0; } } private void Form1_Load(object sender, EventArgs e) { var constr = typeof(myClass).GetConstructor(Type.EmptyTypes); }