I'm looking for an easy way to clone off an IEnumerable<T>
parameter for later reference. LINQ's ToArray
extension method seems like a nice, concise way to do this.
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., Count()
will see if the method implements ICollection<T>
, and if so, will directly read its Count
property; it only iterates the collection if it has to.
Given that mindset of short-circuiting where practical, it seems that, if I call ToArray()
on something that already is an array, ToArray()
might short-circuit and simply return the same array instance. That would technically fulfull the requirements of a ToArray
method.
From a quick test, it appears that, in .NET 4.0, calling ToArray()
on an array does return a new instance. My question is, can I rely on this? Can I be guaranteed that ToArray
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?