Immutable list in .NET: Why are you allowed to add and remove items?

Marcel :

In C#, I just got the need of having an immutable list, meaning that the list can not be changed.

Much like in Java's immutable list: https://www.geeksforgeeks.org/immutable-list-in-java/

From there:

If any attempt is made to add null element in List, UnsupportedOperationException is thrown.

Now, with .NET (at least with Core 2.2) there is also an immutable list, documented here.

They say (emphasis mine):

When you add or remove items from an immutable list, a copy of the original list is made with the items added or removed, and the original list is unchanged.

So, this implementation basically allows changing the list (by getting a manipulated copy each time), as opposed to the java understanding, and what's more, it will mostly go undetected clogging memory.

What's the point in having an immutable list that supports add and remove methods in the first place?

The problem for me here is, that users of my code would get a list, immutable presumably, but out of neglectance would happily add items, which will never made it to the original "repository". This will cause confusion.

I guess the (only) way to go here, to forbid manipulation entirely, and make it clear to the code user, would be to use the IEnumerale interface?

davidxxx :

What's the point in having an immutable list that supports add and remove methods in the first place?

No one but to be conform with the List contract, the implementation even immutable will expose every List methods.
After you have two ways to cope with these modification methods : throwing an exception or guaranteeing the immutability by creating and returning a new List at each modification.

About :

I guess the (only) way to go here, to forbid manipulation entirely, would be to use the IEnumerale interface?

Indeed, in Java you use Iterable (that is close enough) when you want to be able to manipulate a collection of things without a way to change it.
As alternative you can also use an array.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=144659&siteId=1