Click or drag to resize

Immutability Overview

[This is preliminary documentation and is subject to change.]

The Immutability Requirement

Modifying an object that's held in the CondensedCollection's intern pool will cause every other element pointing to that unique value to reflect the same change. This is almost never a desirable outcome.

Caution note Caution

You may hear a little voice in your head whispering, "It'll be OK to use a mutable type. I just won't modify objects in the collection."

Don't listen to that voice.

"But I promise to be careful," says the little voice.

No! Don't do it. You'll forget your promise in two months, or someone else on your team won't know about it, or somewhere you'll reference the CondensedCollection as an IListT and will lose track of what kind of collection you're working with, and your app will break catastrophically. Don't give in to the temptation.

Unfortunately, .NET doesn't give us a way to enforce immutability at compile time or at runtime. There's an experimental Roslyn Analyzer that ships with the library's NuGet package, but it's very rough right now and only detects the simplest, most blatant violations with a warning:

Warning CLDN001

Type 'Foo' is a mutable reference type and should not be used in a CondensedCollection<T>.

...with time this analyzer should become more robust, and hopefully language support for immutability will improve in the not-to-distant future. But for now your program is expected to be on its best behavior.

Tip Tip

It's OK to store mutable structs (like System.Drawing.Point, for example) in a CondensedCollection--the collection returns copies of value types, so they can be safely modified. However, mutable structs are a controversial design choice, and they're frowned upon by many developers in the .NET community (search for "C# mutable struct" and prepare to read a lot of conflicting opinions).