Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I rely on the LINQ ToArray() always returning a new instance?
    primarykey
    data
    text
    <p>I'm looking for an easy way to clone off an <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" rel="noreferrer"><code>IEnumerable&lt;T&gt;</code></a> parameter for later reference. LINQ's <a href="http://msdn.microsoft.com/en-us/library/bb298736.aspx" rel="noreferrer"><code>ToArray</code></a> extension method seems like a nice, concise way to do this.</p> <p>However, I'm not clear on whether it's always guaranteed to return a new array instance. Several of the LINQ methods will check the actual type of the enumerable, and shortcut if possible; e.g., <a href="http://msdn.microsoft.com/en-us/library/bb535181.aspx" rel="noreferrer"><code>Count()</code></a> will see if the method implements <a href="http://msdn.microsoft.com/en-us/library/92t2ye13.aspx" rel="noreferrer"><code>ICollection&lt;T&gt;</code></a>, and if so, will directly read its <a href="http://msdn.microsoft.com/en-us/library/5s3kzhec.aspx" rel="noreferrer"><code>Count</code></a> property; it only iterates the collection if it has to.</p> <p>Given that mindset of short-circuiting where practical, it seems that, if I call <code>ToArray()</code> on something that already <em>is</em> an array, <code>ToArray()</code> might short-circuit and simply return the same array instance. That would technically fulfull the requirements of a <code>ToArray</code> method.</p> <p>From a quick test, it appears that, in .NET 4.0, calling <code>ToArray()</code> on an array <em>does</em> return a new instance. My question is, <strong>can I rely on this?</strong> Can I be guaranteed that <code>ToArray</code> will always return a new instance, even in Silverlight and in future versions of the .NET Framework? Is there documentation somewhere that's clear on this point?</p>
    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. 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