TryGetValueOrCreate

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;

Lastest update in December 2019, inital post in December 2019

Write a comment

I appreciate comments, suggestions, compliments etc. Unfortunately I have no time to reply to them. Useful input will be used for sure!