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?
ReadOnlyCollection<T>(IList<T>) Initializes a new instance of the ReadOnlyCollection<T> class that is a read-only wrapper around the specified list.
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.
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.
IEnumerable<T> is always readonly, by definition. However, the objects inside may be mutable, as in this case.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With