Given this code:
public class Test
{
public T Get1<T>()
{
return Activator.CreateInstance<T>();
}
public T Get2<T>() where T : new()
{
return new T();
}
}
both methods produce exactly the same method body making use of System.Activator
, namely:
.method public hidebysig instance !!T Get1<T> () cil managed
{
.maxstack 8
call !!0 [mscorlib]System.Activator::CreateInstance<!!T>()
ret
}
.method public hidebysig instance !!T Get2<.ctor T> () cil managed
{
.maxstack 8
call !!0 [mscorlib]System.Activator::CreateInstance<!!T>()
ret
}
Why does code using the new()
constraint not compile to the fictional code below?
.method public hidebysig instance !!T Get2<.ctor T> () cil managed
{
.maxstack 1
newobj instance void !!0::.ctor()
ret
}
Does not the constraint <.ctor T>
mean that there has to be a parameterless constructor on the type T
, therefore should not it be okay to just call it as shown above?
Aforementioned behavior occurs when compiled for .NET Framework 4.8 as well as .NET Core (x64) and with the latest (23 Sep 2019) Roslyn compiler.