Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

clr

generics

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

When there is no new() constraint, I understand how it would work. The JIT Compiler sees T and if it's a reference type makes uses the object versions of the code, and specializes for each value type case.

How does it work if you have a new T() in there? Where does it look for?

like image 263
halivingston Avatar asked Sep 26 '22 18:09

halivingston


1 Answers

If you mean, what does the IL look like, the compiler will compile in a call to Activator.CreateInstance<T>.

The type you pass as T must have a public parameterless constructor to satisfy the compiler.

You can test this 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
like image 113
Lasse V. Karlsen Avatar answered Sep 29 '22 08:09

Lasse V. Karlsen