Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we find Int32's Default Constructor using GetConstructor?

Tags:

c#

reflection

In C# we can do something like this:

Int32 i = new Int32();

However the following will return null:

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

Why is this?

I checked the documentation and got no clues as to why this happens.

My results can be illustrated in the following piece of code:

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);
    }
}

The output is :

0

True

like image 425
Aelphaeis Avatar asked Sep 15 '14 01:09

Aelphaeis


1 Answers

Alexei Levenkov posted a really good answer in the comments so I've decided to take the contents and paraphrase them to answer my question. Reference to original Q & A.

Its a bit thick but here is the answer :

Structures do not necessarily have parameter-less constructors. They can have one but C# does not emit one and the compiler does not require one. The C# standard talks about all value types having "an implicit public parameter-less constructor called the default constructor" but it subsequently notes that implementations are not required to generate a constructor calls and that the calls work as if they are constructors although they are not necessarily constructors.

The reason why reflection may not find the constructor method is because it in fact does not exist. The CLR will allow you to instantiate without a constructor and zero fill the memory locations that the object contains.

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

like image 176
Aelphaeis Avatar answered Oct 22 '22 21:10

Aelphaeis