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)?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.CreateInstancemethod.