Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can't, basically. When you create an array, it's always initially populated with the default value for the type - which for a class is always a null reference. For <code>int</code> it's 0, for <code>bool</code> it's false, etc.</p> <p>(If you use an array initializer, that will create the "empty" array and <em>then</em> populate it with the values you've specified, of course.)</p> <p>There are various ways of populating the array by calling the constructor - I would <em>probably</em> just use a foreach loop myself. Using LINQ with Enumerable.Range/Repeat feels a little forced.</p> <p>Of course, you could always <em>write</em> your own population method, even as an extension method:</p> <pre><code>public static T[] Populate&lt;T&gt;(this T[] array, Func&lt;T&gt; provider) { for (int i = 0; i &lt; array.Length; i++) { array[i] = provider(); } return array; } </code></pre> <p>Then you could use:</p> <pre><code>Sample[] samples = new Sample[100].Populate(() =&gt; new Sample()); </code></pre> <p>What I like about this solution:</p> <ul> <li>It's still a single expression, which can be useful in various scenarios</li> <li>It doesn't introduce concepts you don't actually want (like repeating a single value or creating a range)</li> </ul> <p>Of course you could add more options:</p> <ul> <li>An overload which takes a <code>Func&lt;int, T&gt;</code> instead of a <code>Func&lt;T&gt;</code>, passing the index to the provider</li> <li>A non-extension method which creates the array <em>and</em> populates it</li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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