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?
Yes, ToArray
will always return a new array - making it change to return an existing value would be a horribly breaking change, and I'm utterly convinced that the .NET team wouldn't do this. It's an important thing to be able to rely on. It's a shame it's not documented :(
There are lots of subtle bits of behaviour in LINQ to Objects which probably aren't worth relying on, but in this case it's such a massive bit of behaviour, I would be absolutely astonished for it to change.
Short-circuiting is great when it doesn't affect behaviour, but generally LINQ to Objects is pretty good about only optimizing in valid cases. You might want to look at the two posts in my Edulinq series covering optimization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With