Alex Rivera | Logout

How to cast a ReadOnlyCollection<T> to T[]?

Asked 2010-03-11T22:39:36.493
17

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?

c#
Edit
Report

1 Answer

13

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();
answered 2010-03-11T22:46:24.483

Your Answer