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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With