Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Array.ToArray<>() return the original array if it is the same type?

I deal with a framework on a daily basis where we sometimes provide methods that accept IEnumerable<MyBusinessObject> as a parameter in order to show user interfaces, perform calculations etc.

If I pass in an array of MyBusinessObject like so:

MyBusinessObject[] myArray = new MyBusinessObject { obj1, obj2, ..., objN }; frameworkClass.MyMethod(myArray);  ....  public class FrameworkClass {     public void MyMethod(IEnumerable<MyBusinessObject> objs)     {         // Other code that uses the enumerable         MyBusinessObject[] objectArray = objs.ToArray();                     // More code that uses the enumerable     } } 

Does the line objs.ToArray() simply resolve the IEnumerable<MyBusinessObject> back to the original array, or does it copy it to a whole new array, ready for use?

like image 655
Codesleuth Avatar asked Jan 19 '10 10:01

Codesleuth


People also ask

Does toArray copy?

ToArray() This method is used to copy the elements of the ArrayList to a new Object array. The elements are copied using Array. Copy, which is an O(n) operation, where n is Count.

Does toArray create a copy Java?

The toArray() method of Stack class in Java is used to form an array of the same elements as that of the Stack. Basically, it copies all the element from a Stack to a new array.

What is toArray()?

The toArray() method is used to get an array which contains all the elements in ArrayList object in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein.


2 Answers

No, you will always get a new copy of the array, though the objects in it aren't copies, they are the same references as in the original array.

It would be very inconsistent for changes to the returned array to sometimes affect the source and sometimes not. ToList works the same way for the same reason.


You can check source code (as of 2015) if you need to review details: Enumerable.ToArray which in turn creates copy of elements (optimized for ICollection and hence Array[], but still making copy) with internal Buffer class.

like image 138
Neil Barnwell Avatar answered Sep 18 '22 12:09

Neil Barnwell


You will get a new copy of the array if there is one or more element in it. For empty arrays, you might get the same array back, at least in .NET 5:

Console.WriteLine(Object.ReferenceEquals(Array.Empty<string>(), Array.Empty<string>().ToArray())); 

This returns true.

like image 42
Stefan Schultze Avatar answered Sep 18 '22 12:09

Stefan Schultze