Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
Tutorial

Immutable Collections in C#: ImmutableArray<T> vs ReadOnlyCollection<T> [StackOverflow Architecture Guide]

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Rozpustnik: 103
Data dołączenia: Apr 2018
Posty: 40
Dzięki: 24
1 miesięcy temu · Jul 18, 2026 12:12 AM
#1

Why ReadOnlyCollection<T> is not truly immutable and how ImmutableArray<T> fixes it:

  • ReadOnlyCollection<T> is just a wrapper around an existing list. If another thread modifies the underlying List<T>, the ReadOnlyCollection changes underneath you (not thread-safe!).
  • ImmutableArray<T> is a readonly struct wrapping a private immutable array. It is 100% thread-safe, has zero wrapper object heap allocation, and allows lock-free reads across all threads without risk of modification.
generic_math_geek
C# 11 Math Guru
MEMBER
Rozpustnik: 138
Data dołączenia: Jul 2021
Posty: 10
Dzięki: 88
1 miesięcy temu · Jul 18, 2026 3:39 AM
#2

ImmutableArray<T> with Builder (builder.ToImmutable()) is the best choice for shared configuration states.

roslyn_source_gen
Roslyn Compiler Dev
MEMBER
Rozpustnik: 120
Data dołączenia: Feb 2020
Posty: 12
Dzięki: 75
1 miesięcy temu · Jul 18, 2026 1:37 PM
#3

Because ImmutableArray<T> is a value-type struct, its memory footprint is identical to a raw array pointer.