Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 475
Brian Triplett Avatar asked Mar 11 '10 22:03

Brian Triplett


People also ask

What is ReadOnlyCollection?

ReadOnlyCollection<T>(IList<T>) Initializes a new instance of the ReadOnlyCollection<T> class that is a read-only wrapper around the specified list.

How do I make a HashSet read only?

How To Make HashSet Read Only In Java? Collections. unmodifiableSet() method is used to create read only HashSet in java. Below program demonstrates that you will not be able to perform modification operations on read only set and modifications to original set are reflected in read only set also.

Is a readonly collection mutable?

The fact that ReadOnlyCollection is immutable means that the collection cannot be modified, i.e. no objects can be added or removed from the collection.

Is IEnumerable readonly?

IEnumerable<T> is always readonly, by definition. However, the objects inside may be mutable, as in this case.


1 Answers

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();
like image 172
Guffa Avatar answered Oct 05 '22 10:10

Guffa