Get an existing item from a dictionary or create a new value with a default value, using an extension method.
static class extensionMethods
{
public static V TryGetValueOrCreate<K, V>(this Dictionary<K, V> dictionary, K key)
where V : new()
{
V data;
if (!dictionary.TryGetValue(key, out data))
{
data = new V();
dictionary.Add(key, data);
}
return (data);
}
}
The method above can be used using the code below:
public class Item
{
public int test;
};
Dictionary<int,Item> dict = new Dictionary<int,Item>();
Item item = dict.TryGetValueOrCreate(3);
item.test= 123;