Skip to content

Instantly share code, notes, and snippets.

@paulblamire
Created February 20, 2014 21:12
Show Gist options
  • Save paulblamire/9123271 to your computer and use it in GitHub Desktop.
Save paulblamire/9123271 to your computer and use it in GitHub Desktop.
Dictionary Extensions
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Everhaven.Utility
{
internal static class DictionaryExtensions
{
public static V GetOrNull<K, V>(this Dictionary<K, V> dictionary, K key)
{
V existingValue;
if (dictionary.TryGetValue(key, out existingValue))
{
return existingValue;
}
else
{
return default(V);
}
}
public static V GetOrCreate<K, V>(this Dictionary<K, V> dictionary, K key, Func<V> valueFactory)
{
if (key == null) throw new ArgumentException("get or create must supply a key for the dictionary");
V existingValue;
if (!dictionary.TryGetValue(key, out existingValue))
{
V newValue = valueFactory();
dictionary.Add(key, newValue);
return newValue;
}
else
{
return existingValue;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment