I have IEnumerable<Object>
and need to pass to a method as a parameter but this method takes IReadOnlyCollection<Object>
Is it possible to convert IEnumerable<Object>
to IReadOnlyCollection<Object>
?
The IReadOnlyCollection interface extends the IEnumerable interface and represents a basic read-only collection interface. It also includes a Count property apart from the IEnumerable members as shown in the code snippet given below.
IEnumerable<T> is always readonly, by definition. However, the objects inside may be mutable, as in this case.
Represents a read-only collection of elements that can be accessed by index.
It demonstrates that IReadOnlyList<T> can change even during duration of a single method! Remember not to use ReadOnlyCollection<T> class to create a defensive copy. This class is only a wrapper - it does not copy the actual data. These types are truly immutable, they never change their contents after they are created.
One way would be to construct a list, and call AsReadOnly()
on it:
IReadOnlyCollection<Object> rdOnly = orig.ToList().AsReadOnly();
This produces ReadOnlyCollection<object>
, which implements IReadOnlyCollection<Object>
.
Note: Since List<T>
implements IReadOnlyCollection<T>
as well, the call to AsReadOnly()
is optional. Although it is possible to call your method with the result of ToList()
, I prefer using AsReadOnly()
, so that the readers of my code would see that the method that I am calling has no intention to modify my list. Of course they could find out the same thing by looking at the signature of the method that I am calling, but it is nice to be explicit about it.
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