If I have a type parameter constraint new()
:
void Foo() where T : new()
{
var t = new T();
}
Is it true that
Yes. It does for reference types.
Using ILSpy on the following release-compiled code:
public static void DoWork() where T: new()
{
T t = new T();
Console.WriteLine(t.ToString());
}
Yielded
.method public hidebysig
instance void DoWork<.ctor T> () cil managed
{
// Method begins at RVA 0x2064
// Code size 52 (0x34)
.maxstack 2
.locals init (
[0] !!T t,
[1] !!T CS$0$0000,
[2] !!T CS$0$0001
)
IL_0000: ldloca.s CS$0$0000
IL_0002: initobj !!T
IL_0008: ldloc.1
IL_0009: box !!T
IL_000e: brfalse.s IL_001b
IL_0010: ldloca.s CS$0$0001
IL_0012: initobj !!T
IL_0018: ldloc.2
IL_0019: br.s IL_0020
IL_001b: call !!0 [mscorlib]System.Activator::CreateInstance()
IL_0020: stloc.0
IL_0021: ldloca.s t
IL_0023: constrained. !!T
IL_0029: callvirt instance string [mscorlib]System.Object::ToString()
IL_002e: call void [mscorlib]System.Console::WriteLine(string)
IL_0033: ret
} // end of method Program::DoWork
Or in C#:
public void DoWork() where T : new()
{
T t = (default(T) == null) ? Activator.CreateInstance() : default(T);
Console.WriteLine(t.ToString());
}
JIT will create different compiled instructions for each different value type parameter passed in, but will use the same instructions for reference types -- hence the Activator.CreateInstance()