CKTIS / C#
GetValueOrDefault on IReadOnlyDictionary
Look up a dictionary value with a fallback and know when to distinguish a missing key from a stored `null`.
Version: C# 12 and .NET 8; later runtimes may add compatible features
Syntax
using System.Collections.Generic;
// Extension signatures on System.Collections.Generic.CollectionExtensions:
public static TValue? GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key);
public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue);
// Extension call and equivalent static call:
dictionary.GetValueOrDefault(key);
CollectionExtensions.GetValueOrDefault(dictionary, key);
dictionary.GetValueOrDefault(key, defaultValue);
CollectionExtensions.GetValueOrDefault(dictionary, key, defaultValue);In C# 12 and .NET 8, dictionary.GetValueOrDefault(key) calls an extension method on CollectionExtensions in System.Collections.Generic, not an instance member of IReadOnlyDictionary<TKey, TValue>. Bring the extension into scope with using System.Collections.Generic; or use the equivalent static call CollectionExtensions.GetValueOrDefault(dictionary, key) to make its origin explicit. Dictionary<TKey, TValue> implements the read-only interface, but a variable declared only as IDictionary<TKey, TValue> does not expose this extension. Read-only access does not guarantee that the underlying collection is immutable.
Both overloads return the stored value when the key exists, even if that value is null. When the key is missing, the overload without a fallback returns default(TValue) (for example, null for a reference type or 0 for int); the other returns the supplied defaultValue. A fallback argument expression is evaluated before the call, even on a hit. By contrast, dictionary.GetValueOrDefault(key) ?? fallback requires a lookup result that can be the left operand of ??, such as Cmd? in the example. In that case, it evaluates and uses fallback only when the lookup returns null, including when null is the stored value. For TValue = int, this form does not compile because the lookup returns a non-nullable int.
If absence must be distinguished from a stored value equal to the default or fallback, use TryGetValue(key, out var value) and check the returned bool. A missing key is not an exception in GetValueOrDefault, but a null dictionary causes ArgumentNullException. Dictionary<TKey, TValue> also rejects a null key with that exception.
With #nullable enable, Cmd? means a Cmd reference may be null. This is an annotation for compiler analysis, not a wrapper or a runtime check. The dictionary extension is distinct from the instance method Nullable<T>.GetValueOrDefault() for nullable value types.
In a mini-DSL architecture, a parser checks the text against the grammar and builds an abstract syntax tree (AST). An evaluator interprets only supported nodes and resolves command names through a registry. Do not pass the text to JavaScript eval. If an unknown command is an error, use TryGetValue to report it rather than silently choosing a fallback command.
Examples
#nullable enable
using System;
using System.Collections.Generic;
IReadOnlyDictionary<string, Cmd?> commands = new Dictionary<string, Cmd?>(StringComparer.Ordinal)
{
["print"] = new Cmd("PRINT"),
["disabled"] = null
};
var fallback = new Cmd("FALLBACK");
Console.WriteLine($"hit: {Show(commands.GetValueOrDefault("print"))}");
Console.WriteLine($"missing: {Show(commands.GetValueOrDefault("missing"))}");
Console.WriteLine($"missing with fallback: {Show(commands.GetValueOrDefault("missing", fallback))}");
Console.WriteLine($"stored null with fallback: {Show(commands.GetValueOrDefault("disabled", fallback))}");
Console.WriteLine($"static: {Show(CollectionExtensions.GetValueOrDefault(commands, "missing", fallback))}");
Console.WriteLine($"presence of missing: {commands.TryGetValue("missing", out _)}");
Console.WriteLine($"presence of disabled: {commands.TryGetValue("disabled", out _)}");
static string Show(Cmd? cmd) => cmd?.Name ?? "<null>";
sealed record Cmd(string Name);
Result
hit: PRINT missing: <null> missing with fallback: FALLBACK stored null with fallback: <null> static: FALLBACK presence of missing: False presence of disabled: True
`missing` is absent, while `disabled` is stored as `null`. Only the absent key receives `FALLBACK`; the two `TryGetValue` calls show which key exists.
Related lessons
- C# · Lesson 57 · Advanced · Version: 3
Sources
- CollectionExtensions.GetValueOrDefault Method
- IReadOnlyDictionary<TKey,TValue> Interface
- IReadOnlyDictionary<TKey,TValue>.TryGetValue(TKey, TValue) Method
- Dictionary<TKey,TValue>.TryGetValue(TKey, TValue) Method
- How to implement and call a custom extension method
- Nullable reference types
- ?? and ??= operators - the null-coalescing operators
- Get started with syntax analysis (Roslyn APIs)
- C# language versioning
- dotnet new <TEMPLATE>