C # - How are generic files generated with a new () machine code restriction?

public T Foo<T, U>(U thing) where T : new() { return new T(); } 

When there is no new() constraint, I understand how it will work. The JIT compiler sees T, and if it uses a reference type, uses object versions of the code and specializes in each case of type value.

How does it work if you have a new T ()? Where is he looking?

+5
source share
1 answer

If you mean what IL looks like, the compiler will compile when Activator.CreateInstance<T> called.

The type you pass as T must have an open constructor with no parameters in order to satisfy the compiler.

You can check this out in Try Roslyn :

 public static T Test<T>() where T : class, new() { return new T(); } 

becomes:

 .method public hidebysig static !!T Test<class .ctor T> () cil managed { // Method begins at RVA 0x2050 // Code size 6 (0x6) .maxstack 8 IL_0000: call !!0 [mscorlib]System.Activator::CreateInstance<!!T>() IL_0005: ret } // end of method C::Test 
+4
source

All Articles