How to distinguish ReadOnlyCollection from <T> to T []?
4 answers
No, it is not possible to convert ReadOnlyCollection to an array without iterating it. This would make the collection a writable collection, breaking the read-only contract.
There are different ways to iterate through a collection, which eliminates the need to write a loop, for example using the CopyTo method.
int[] collection = new int[theObject.TheProperty.Count];
theObject.TheProperty.CopyTo(collection, 0);
Or the ToArray extension method:
int[] collection = theObject.TheProperty.ToArray();
+8
If you use later versions the .NET framework ReadOnlyCollection<T>implements IEnumerable<T>. IEnumerable<T>has an extension method ToArray(). So you should use this extension method so ...
var readOnly = new ReadOnlyCollection<int>(new List<int>() {1,2,3,4,5});
var myArray = readOnly.ToArray();
+1