5
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?

Yael
  • 1,566
  • 3
  • 18
  • 25
halivingston
  • 3,727
  • 4
  • 29
  • 42

1 Answers1

4

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
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • Follow up question for this http://stackoverflow.com/questions/32553686/c-sharp-why-does-a-class-new-constraint-use-activator-createinstancet. – Rahul Sep 13 '15 at 19:31