using System.Collections;
using System.Collections.Generic;
static int count {get;set;} = 1;
public string someProp {get;set;}
public override string ToString()
return nameof(SomeEntity) + ": " + id + " - " + someProp;
public static void Main()
Console.WriteLine("Hello World");
var myDict = new Dictionary<string, SomeEntity>();
var x = myDict.GetOrAddNew("myKey");
var x1 = myDict.GetOrAddNew("myKey1", null);
var x2 = myDict.GetOrAddNew("myKey2", default);
var x3 = myDict.GetOrAddNew("myKey3", new SomeEntity{someProp = "Reee"});
foreach(var kvp in myDict)
Console.WriteLine(kvp.Value.ToString());
public static class DictionaryExtensions
public static TValue GetOrAddNew<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default)
=> dict.GetOrAdd(key, (values, innerKey) => EqualityComparer<TValue>.Default.Equals(default(TValue), defaultValue) ? new TValue() : defaultValue);
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default)
=> dict.GetOrAdd(key, (values, innerKey) => defaultValue);
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TValue> valueProvider)
=> dict.GetOrAdd(key, (values, innerKey) => valueProvider());
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TKey, TValue> valueProvider)
=> dict.GetOrAdd(key, (values, innerKey) => valueProvider(key));
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<IDictionary<TKey, TValue>, TKey, TValue> valueProvider)
if (dict == null) throw new ArgumentNullException(nameof(dict));
if (key == null) throw new ArgumentNullException(nameof(key));
if (valueProvider == null) throw new ArgumentNullException(nameof(valueProvider));
if (dict.TryGetValue(key, out var foundValue))
dict[key] = valueProvider(dict, key);