Build with an Azure free account. Get USD200 credit for 30 days and 12 months of free services.

Start free today

C# Highlights: Immutable Collections

Play C# Highlights: Immutable Collections

The Discussion

  • User profile image
    Tia

    ImmutableList<T> is immutable as the name specified. Add and Remove method just returns new list from the original one with the element added and removed accordingly, and leaves the original list unmodified.

  • User profile image
    Dan

    He shows how to restrict values from being modified.

    She says "That's so cool I'm speechless."

  • User profile image
    P S

    Thanks, Tia, wouldn't have known that without your comment!

  • User profile image
    bekirozturk
    I agree with the other comments that the point about ImmutableList is a bit misleading. Add and remove doesn't change the list, it creates a new one. If we ignore the return value as you have shown in the example, it just turns into a code that does nothing.

    Here are my 2 other cents: Readonly collections can be modified as long as you have a reference to the underlying collection. If you have received a read only list from an API, that means _you_ cannot change the list. Having a reference to the underlying collection, the API can continue to do whatever it wants to it.

    Immutable collections, on the other hand, are truly immutable. When you acquire a reference to an immutable collection you know that neither can you change it, nor can the code that passed it to you.

Add Your 2 Cents