Nullable Dictionary
DictionaryNullable is a (niche appeal) class written to wrap the logic of checking for existence of keys to a conditional to check if the value is null, for circumstances where
the values are never null (or the value type doesn't permit nulls) or
the presence of a key or its absence is logically indistinguishable and irrelevant from the value being null e.g.
var myDict = new DictionaryNullable<string, string> {{"key1", "value1"}}; string val = (myDict["key2"] ?? (myDict["key2"] = "value2"));
It extends Dictionary and overrides the collection reference operator []:
public sealed class DictionaryNullable<TK, T> : Dictionary<TK, T> { public new T this[TK key] { get { if (ContainsKey(key)) return base[key]; return default(T); } set { base[key] = value; } } }
Complete class code:
public sealed class DictionaryNullable<TK, T> : Dictionary<TK, T> where TK : IComparable<TK> { public static DictionaryNullable<TK, T> FromDictionary(Dictionary<TK, T> actual) { return new DictionaryNullable<TK, T>(actual); } public Dictionary<TK, T> ToDictionary() { return new Dictionary<TK, T>(this); } public DictionaryNullable() : base() { } public DictionaryNullable(SerializationInfo info, StreamingContext context) : base(info, context) { } public DictionaryNullable(int capacity) : base(capacity) { } public DictionaryNullable(int capacity, IEqualityComparer<TK> iEq) : base(capacity, iEq) { } public DictionaryNullable(IDictionary<TK, T> iDic, IEqualityComparer<TK> iEq) : base(iDic, iEq) { } public DictionaryNullable(IDictionary<TK, T> iDic) : base(iDic) { } public new T this[TK key] { get { if (ContainsKey(key)) return base[key]; return default(T); } set { base[key] = value; } } }









