using System.Collections.Generic;
using System.Runtime.InteropServices;
public static class Program
public static void Main()
Dictionary<string, List<int>> dictionary = new();
list = dictionary.GetOrAdd("A", key => new List<int>());
list = dictionary.GetOrAdd("A", key => new List<int>());
list = dictionary.GetOrAdd("B", (key, arg) => new List<int>(arg), factoryArgument: 10);
Console.WriteLine($"dictionary: {String.Join(", ", dictionary.Select(e => $"[{e.Key}: [{String.Join(", ", e.Value)}]]"))}");
public static TValue GetOrAdd<TKey, TValue>(
this Dictionary<TKey, TValue> dictionary,
Func<TKey, TValue> valueFactory)
ArgumentNullException.ThrowIfNull(dictionary);
ArgumentNullException.ThrowIfNull(valueFactory);
ref TValue value = ref CollectionsMarshal
.GetValueRefOrAddDefault(dictionary, key, out bool exists);
try { value = valueFactory(key); }
catch { dictionary.Remove(key); throw; }
public static TValue GetOrAdd<TKey, TValue, TArg>(
this Dictionary<TKey, TValue> dictionary,
Func<TKey, TArg, TValue> valueFactory,
ArgumentNullException.ThrowIfNull(dictionary);
ArgumentNullException.ThrowIfNull(valueFactory);
ref TValue value = ref CollectionsMarshal
.GetValueRefOrAddDefault(dictionary, key, out bool exists);
try { value = valueFactory(key, factoryArgument); }
catch { dictionary.Remove(key); throw; }