C# Reference ยท Collections
CollectionsMarshal class
Reference for C# CollectionsMarshal: view a List<T> as a Span, update dictionary values in place with ref returns, and the safety rules that come with it.
System.Runtime.InteropServices.CollectionsMarshal is a static class that exposes the internals of List<T> and Dictionary<TKey,TValue> for performance-sensitive code. It lets you treat a list's backing array as a Span<T> and get a ref to a dictionary slot, so you can read and modify without copying or hashing twice.
These methods bypass safety checks that normal collection members perform. Use them when a profiler shows a real cost, and keep the unsafe part small.
using System.Runtime.InteropServices; var list = new List<int> { 1, 2, 3 }; Span<int> span = CollectionsMarshal.AsSpan(list); span[0] = 100; // writes straight into the list
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static Span<T> AsSpan<T>(List<T>? list); public static void SetCount<T>(List<T> list, int count); public static ref TValue? GetValueRefOrNullRef<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TKey key); public static ref TValue? GetValueRefOrAddDefault<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TKey key, out bool exists);
| Name | Description |
|---|---|
list |
The list whose elements the span covers, or whose length changes. |
count |
New element count for SetCount. |
dictionary, key |
The dictionary and the key whose slot you want. |
exists |
true if the key was already present. |
Returns: AsSpan returns a span over the first Count items (an empty span for null). The GetValueRef... methods return a ref to the stored value; GetValueRefOrNullRef returns a null reference when the key is absent (test with Unsafe.IsNullRef, in System.Runtime.CompilerServices).
Errors: SetCount throws ArgumentOutOfRangeException for a negative count. A stale span or ref does not throw: it silently reads or writes memory that the collection no longer uses.
Usage notes
- A span from
AsSpanis valid only until the list changes its backing array: anyAdd,Insert,Remove,Clear,Capacitychange or sort that resizes can make it stale. Do not keep it across such calls and do not store it in fields. - Because
Span<T>is aref struct, it cannot be used inasyncmethods across anawaitor in lambdas that capture it. - A ref from a dictionary slot is invalid after the dictionary adds, removes or resizes. Never modify the dictionary while holding it. Note that
GetValueRefOrAddDefaultitself may add an entry. - The common use case is a counter dictionary:
ref+++does one lookup instead of theTryGetValueplus indexer-set pair. SetCountexposes uninitialized-looking slots: new items are not initialized by you (they hold default values or old data from the backing array, so do not rely on which); fill them before reading.- Updating a list through a span does not change its internal version number, so an active
foreachover the list does not throw (see modifying while enumerating). - Prefer normal indexers and
CollectionExtensions.TryAddunless profiling shows the saving matters.
Related
- List
- Dictionary<TKey,TValue>
- Span
- Collection complexity
- Spans and memory in the tutorial