Why can't we find Int32 Default Constructor with GetConstructor?

In C #, we can do something like this:

Int32 i = new Int32(); 

However, the following returns null :

 typeof(Int32).GetConstructor(new Type[0]) 

Why is this?

I checked the documentation and did not understand why this is happening.

My results can be illustrated in the following code snippet:

 using System; public class Program { public static void Main() { Int32 i = new Int32(); Console.WriteLine(i); Console.WriteLine(typeof(Int32).GetConstructor(new Type[0]) == null); } } 

Output:

0

True

+6
source share
1 answer

Alexey Levenkov wrote a wonderful answer in the comments, so I decided to accept the content and rephrase them to answer my question. Link to the original Q and A.

Its a little thick, but here is the answer:

Structures do not necessarily contain constructors without parameters. They may have one, but C # does not emit one, and the compiler does not require it. The C # standard talks about all types of values ​​that have an β€œimplicit public constructor without parameters, called the default constructor,” but he later notes that implementations are not required to create constructor calls and that the calls work as if they were constructors, although they are not necessarily designers.

The reason that reflection cannot find the constructor method is because it does not actually exist. The CLR will allow you to instantiate without a constructor and fill zero the memory cells that the object contains.

Update: I would like to note that Jon Skeet also answered a question related to this here

+5
source

Source: https://habr.com/ru/post/975265/


All Articles