× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Creating an instance of a generic type

Michael Perrenoud
Feb 06, 2015
<p>One approach would be to use the <a href="http://msdn.microsoft.com/en-us/library/sd2w2ew5.aspx" rel="nofollow"><code>new</code></a> constraint for <code>T</code> here. So, for example, the <code>class</code> or <code>method</code> here that defines <code>T</code> needs to add a constraint like this:</p> <pre><code>where T : new() </code></pre> <p>Please note that you <strong>must</strong> have a parameterless constructor on <code>T</code>, <em>and</em> it cannot be <code>abstract</code>:</p> <blockquote> <p>The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.</p> </blockquote> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/25723470/Creating%20an%20instance%20of%20a%20generic%20type/25723563">Stack Overflow</a>.</p>
comments powered by Disqus