The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.
Can you guys give me a sample scenario when this constraint is needed?
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.
This is essentially what the
new()constraint boils down to:Now, you’re not allowed to pass arguments to the constructor. If you nevertheless want to initialize the newed object, you could achieve this e.g. by introducing a further constraint:
Note that another way of instantiating an object is via
Activator.CreateInstance, which gives you some more freedom, such as passing arguments directly to a constructor.Activator.CreateInstancedoes not strictly require thenew()constraint; however, the type being instantiated still needs to provide a suitable constructor.