Prohibit list changes in C #

I have Linkedlist objects (can be changed to any other type of collection as long as it keeps the input order) in assembly A (DLL).

When Assembly B creates an object from a class that contains the LinkedList mentioned, it assigns a method to send some information. One of the arguments this method takes is called LinkedList.

Now I want this method in assembly B to be able to read this LinkedList (navigate through it and make stuff based on its contents), however I need this method not to change the data in the list.

While I use assembly A right now, when and if it becomes publicly available, I need to prevent data from being changed outside of my assembly so that no third-party users using the library can intercept the results in the assembly.

I am mainly looking to β€œseal” a parameter that brings a LinkedList from assembly A to assembly B

Is there any reason?

+4
source share
5 answers
new List<T>(linkedList).AsReadOnly(); 
+5
source

I think returning IEnumerable<T> instead of List<T> should fix your problem. The easiest way:

 foreach( var t in list ) yield t; 

This way you will only return the counter. The consumer will not be able to change the contents of the list.

+2
source

If you can go from LinkedList<T> to List<T> , you can use the AsReadOnly() method to create a read-only wrapper for your list. The wrapper is lightweight, does not require copying and immediately reflects changes in the main collection:

 List<MyClass> originalList = ... IList<MyClass> readOnly = originalList.AsReadOnly(); 
+2
source

Instead of passing the real linked list to callback method B, pass a copy. This way, B can do whatever it wants with the list without changing the original list.

Making a copy of the linked list is easy using the LinkedList (IEnumerable) constructor:

 var copy = new LinkedList<MyType>(originalList); 

Obviously, list items can be changed by B if they are mutable, but I'm sure you know that.

+1
source

Can you post some code.

It looks like you want to let them work with a copy of the data. Thus, if they somehow change it, the original copy remains unchanged.

Look at the ICloneable interface to duplicate an object and create a completely new linked list with copies of all the original content and pass it back to assembly B.

0
source

Source: https://habr.com/ru/post/1432764/


All Articles