Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable to IReadOnlyCollection

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> ?

like image 851
Mohamed Badr Avatar asked Aug 21 '15 04:08

Mohamed Badr


People also ask

What is IReadOnlyCollection?

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.

Is IEnumerable ReadOnly?

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

What is IReadOnlyList C#?

Represents a read-only collection of elements that can be accessed by index.

Is IReadOnlyList immutable?

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.


1 Answers

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.

like image 87
Sergey Kalinichenko Avatar answered Sep 16 '22 20:09

Sergey Kalinichenko