.NET Fiddle

CSharp · Console

/Program.cs

#nullable enable
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

public static class Program
{
    public static void Main()
    {
        var dict = new Dictionary<int, char>();
        dict[1] = 'A';
        dict[2] = 'B';
        Console.WriteLine($"Before: {String.Join(", ", dict)}");
        try
        {
            foreach (var key in new int[] { 1, 2, 3, 4 })
            {
                _ = dict.GetOrAdd(key, (k) =>
                {
                    if (k == 4) throw new Exception();
                    return (char)(k + 64);
                });
            }
        }
        catch
        {
            Console.WriteLine($"After:  {String.Join(", ", dict)}");
        }
    }

    public static TValue GetOrAdd<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> valueFactory)
        where TKey : notnull
    {
        if (dictionary == null)
        {
            throw new ArgumentNullException(nameof(dictionary));
        }

        if (valueFactory == null)
        {
            throw new ArgumentNullException(nameof(valueFactory));
        }

        ref TValue? value = ref CollectionsMarshal.GetValueRefOrAddDefault(dictionary, key, out bool exists);
        if (!exists)
        {
            value = valueFactory(key);
        }

        return value!;
    }
}
;