If I have a type parameter constraint new()
:
void Foo<T>() where T : new()
{
var t = new T();
}
Is it true that new T()
will internally use the Activator.CreateInstance
method (i.e. reflection)?
If I have a type parameter constraint new()
:
void Foo<T>() where T : new()
{
var t = new T();
}
Is it true that new T()
will internally use the Activator.CreateInstance
method (i.e. reflection)?
Yes. It does for reference types.
Using ILSpy on the following release-compiled code:
Yielded
Or in C#:
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()
Yes, this is true. Edit 2: Here's a good explanation of the how and why.
http://www.simple-talk.com/community/blogs/simonc/archive/2010/11/17/95700.aspx
For verification I compiled the following method:
And this is the generated IL when compiled with the C# compiler in .NET 3.5 SP1:
Edit: The C# 4 compiler creates slightly different, but similar, code:
In the case of a value type it doesn't use the activator but just returns the
default(T)
value, otherwise it invokes theActivator.CreateInstance
method.