CKTIS / C#
IReadOnlyDictionary<TKey, TValue> — a dictionary exposed for reading
IReadOnlyDictionary<TKey, TValue> exposes key–value pairs for reading without mutation operations. It does not guarantee immutable data. Learn lookup options and CollectionExtensions.GetValueOrDefault.
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
IReadOnlyDictionary<TKey, TValue> view = dictionary;
TValue value = view[key];
bool found = view.TryGetValue(key, out TValue result);
TValue fallback = view.GetValueOrDefault(key, defaultValue);IReadOnlyDictionary<TKey, TValue> in System.Collections.Generic describes access to pairs with unique keys. It exposes Count, Keys, Values, an indexer, ContainsKey, and TryGetValue. Iteration yields KeyValuePair<TKey, TValue>; the interface specifies no ordering.
Read-only does not mean immutable. The interface exposes no mutation operations, but an underlying Dictionary<TKey, TValue> can change through another reference. Assigning it to the interface creates neither a copy nor a snapshot and does not freeze objects stored as values.
When a key might be absent, use TryGetValue(key, out value): its bool result distinguishes a missing entry from a stored default value. CollectionExtensions.GetValueOrDefault is an extension method, not an interface member. To use extension-method syntax, the method must be in scope at the call site, for example because the calling code is in the System.Collections.Generic namespace or because that namespace is imported with using System.Collections.Generic; or global using System.Collections.Generic;. For a missing key, GetValueOrDefault(key) returns default(TValue), whereas GetValueOrDefault(key, defaultValue) returns the supplied fallback. Neither overload inserts an entry; a null dictionary causes ArgumentNullException.
The .NET 10 example demonstrates both overloads, detection of an existing entry containing 0, and visibility of a later change to the underlying dictionary. It requires no preview language features.
Examples
using System;
using System.Collections.Generic;
var stock = new Dictionary<string, int>
{
["pen"] = 3,
["paper"] = 0
};
IReadOnlyDictionary<string, int> view = stock;
Console.WriteLine(view["pen"]);
Console.WriteLine(view.GetValueOrDefault("eraser"));
Console.WriteLine(view.GetValueOrDefault("eraser", -1));
Console.WriteLine(view.TryGetValue("paper", out int count));
Console.WriteLine(count);
stock["pen"] = 5;
Console.WriteLine(view["pen"]);Result
3 0 -1 True 0 5
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.