Read the syntax
ReadOnlyCollection<T> prevents modification through its interface but can still reflect changes to the underlying collection. A read-only view is not an immutable snapshot. Use a .NET 8+ console project; replace Program.cs with this C# example.
The wrapper shares the original list. The caller cannot add through view, but source still controls the contents.
Syntax
ReadOnlyCollection<T> view = list.AsReadOnly();Examples
Read-Only Collection Views
Use a .NET 8+ console project; replace Program.cs with this C# example.
using System;
using System.Collections.Generic;
var source = new List<string> { "A" };
var view = source.AsReadOnly();
Console.WriteLine(view.Count);
source.Add("B");
Console.WriteLine(view.Count);
Console.WriteLine(view[1]);- Expected output: 1 2 B
- The wrapper shares the original list. The caller cannot add through view, but source still controls the contents.
- Copy data first when callers need a stable snapshot.
Best practices
- Copy data first when callers need a stable snapshot.
- Do not equate a read-only interface with thread safety.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference