Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Why does a class, new() constraint use Activator.CreateInstance<T>()? [duplicate]

Tags:

c#

clr

jit

I just asked C# - How do generics with the new() constraint get machine code generated?

After thinking about this for a while, I'm wondering why the C# Compiler emitted IL like that.

Why couldn't it say some IL like: "Call T's default constructor"?

like image 915
halivingston Avatar asked Oct 31 '22 19:10

halivingston


1 Answers

There is no such instruction in CIL (http://www.ecma-international.org/publications/standards/Ecma-335.htm).

Assuming we can add one, an another implementation of this could be that in the Type's VTable we make the default constructor be indexed at index 0, and then the JIT can assume this information and emit code that does a VTable lookup, pick index 0 and call the function located at address pointed by this entry 0 in the VTable.

As you can see this requires a change in CLR data structures, possibly each object's layout, and likely a different solution for value types (I'm ignoring that case, because you specifically say class and new().

like image 194
mjsabby Avatar answered Nov 08 '22 13:11

mjsabby