Readonly LinkedList Browser. How?

.NET v2

When the list has a very useful (4 me) method AsReadOnly () LinkedList does not have such a method.

Is there a way to "quickly" connect an internal LinkedList to read only from external code?

+4
source share
3 answers

ReadOnlyCollection<T> takes an argument of IList<T> as a constructor. LinkedList<T> does not implement this interface. List<T> has a constructor overload that takes an IEnumerable<T> argument as an argument, and LinkedList<T> implements this interface. So the following should work:

 LinkedList<int> linked = new LinkedList<int>(); // populate the list ReadOnlyCollection<int> readOnly = new ReadOnlyCollection<int>( new List<int>(linked)); 

It uses an instance of List<T> to wrap items in the ReadOnlyCollection<T> constructor.

+4
source

Why not just return an IEnumerable<T> ? If you just want users to list without changing it *, IEnumerable is the obvious choice.

If you want to have a read-only interface on the LinkedList interface, you can wrap the LinkedList, forward the read-only methods to a packed list, and reject any changes.

*) Keep in mind that neither ReadOnlyCollection nor IEnumerable will allow callers to change the state of objects in the case of a set of reference types. If objects also need to be read, you need to implement this as part of your type.

+8
source

LinkedList<T> does not implement IList , and therefore, there is no way to do this quickly. If you add your LinkedList to the list, you are likely to lose the necessary functionality.

LinkedList<T> does not offer you anything to subclass, so you will need to write your own. I assume the following query: "Can you show me how to do this"

0
source

All Articles