using System.Collections.Generic;
using System.Runtime.InteropServices;
public static void Main()
Dictionary<int, string> d = new();
ref string s = ref d.GetValueRefOrAddDefault(42, out var exists);
s = exists ? "Still the answer" : "The answer";
Console.WriteLine(JsonSerializer.Serialize(d));
public static class Extensions
public static ref TValue GetValueRefOrAddDefault<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key)
=> ref CollectionsMarshal.GetValueRefOrAddDefault(dictionary, key, out _);