Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Update:</strong></p> <p>I removed the constraint of <code>new()</code> to accept a class without <strong>parameterless constructor</strong>. However, this would also accept an abstract class or an interface be used as the type parameter, and it will throw the exception at runtime if the type cannot be instantiated. </p> <p>One thing further to mention is, the <code>CreateArray&lt;T&gt;</code> method would <strong>also deal with value types</strong>; that is, except pointer types and the types which have <code>TypeAttributes.Abstract</code><sup>1</sup> attribute, you can create any type of array with it. </p> <p><sup>1</sup>: Interfaces are also abstract. Static classes are abstract &amp; sealed. </p> <hr> <p>The difference is that <code>int</code> is a value type, but your <code>class</code> might not be. </p> <p>Declare <code>MyClass</code> as <code>struct MyClass{ }</code>, then it would behaves as same as you create an <code>int</code> array. </p> <p>If you do want to create an array of reference types, then the following code just do that: </p> <pre><code>public static class TestClass { public static T[] CreateArray&lt;T&gt;(int length, params object[] args) { var elementType=typeof(T); var array=(T[])Array.CreateInstance(elementType, length); for(; length--&gt;0; array[length]=(T)Activator.CreateInstance(elementType, args)) ; return array; } public static void TestMethod() { var array=CreateArray&lt;MyClass&gt;(5, /* default arguments */ ); } } </code></pre> <p>The default argument are the arguments that you are passing to the constructor. The code creates an array, then create instances of the type with the given arguments and initialize the array with the instances. </p> <p>Note that <code>length</code> are passed as the array size, and then used as index in the for-loop. </p> <p>The documentation: </p> <ul> <li><p><a href="http://msdn.microsoft.com/library/wcxyzt4d.aspx" rel="nofollow">Activator.CreateInstance</a></p></li> <li><p><a href="http://msdn.microsoft.com/library/zb3cfh7k.aspx" rel="nofollow">Array.CreateInstance</a></p></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload