Tutorial :How to cast a ReadOnlyCollection to T[]?


I have a class with a ReadOnlyCollection property. I need to convert that ReadOnlyCollection into a int[]. How can this be done? Is it possible to do this without iterating over the collection?


No, it's not possible to convert a ReadOnlyCollection to an array without iterating it. That would turn the collection to a writable collection, breaking the contract of being read-only.

There are different ways of iterating the collection that spares you of writing the loop yourself, for example using the CopyTo method

int[] collection = new int[theObject.TheProperty.Count];  theObject.TheProperty.CopyTo(collection, 0);  

Or the extension method ToArray:

int[] collection = theObject.TheProperty.ToArray();  


Sure using a LINQ extension method myReadOnlyCollection.ToArray().


There aren't any ways without iterating. There is a built-in method to do this though:

T[] myArray;  myCollection.CopyTo(myArray, 0);  

or using Linq:

var myArray = myCollection.ToArray();  


If you're in the later versions of the .NET framework ReadOnlyCollection<T> implements IEnumerable<T>. IEnumerable<T> has an extension method ToArray(). So you'd use that extension method like so...

var readOnly = new ReadOnlyCollection<int>(new List<int>() {1,2,3,4,5});  var myArray = readOnly.ToArray();  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »