Skip to content

Instantly share code, notes, and snippets.

@chrisfcarroll
Created June 19, 2024 09:23
Show Gist options
  • Save chrisfcarroll/b32892234ea5f3f076d5639514029760 to your computer and use it in GitHub Desktop.
Save chrisfcarroll/b32892234ea5f3f076d5639514029760 to your computer and use it in GitHub Desktop.
A C# DDictionary<K,V> is a Dictionary<K,V> which, if you try to read an empty entry, returns default(V) instead of throwing an exception.
using System.Collections.Generic;
/// <summary>
/// A <see cref="Dictionary{TKey,TValue}&lt;K,V>"/> which, if you try to read
/// an empty entry, returns default(V) instead of throwing an exception.
/// </summary>
/// <remarks>
/// If you cast a <see cref="DDictionary{K,V}"/> to a <see cref="Dictionary{TKey,TValue}"/>
/// then reading an empty entry will throw.
/// <code>
/// var x= new DDictionary&lt;int,string>();
/// Console.WriteLine(x[2]); // prints null
/// try {
/// Console.WriteLine(((Dictionary&lt;int, string>)x)[2]);
/// }
/// catch(Exception e){ Console.WriteLine("This one threw " + e.Message); }
/// Console.WriteLine(((IDictionary)x)[2]); // prints null
/// </code>
/// </remarks>
public class DDictionary<K,V> : Dictionary<K,V>
{
/// <returns><c>base[key]</c> if base.ContainsKey(key),
/// or <c>default(V)</c> if not.
/// </returns>
public new V this[K key]
{
get => (base.ContainsKey(key)) ? base[key] : default(V);
set => base[key]=value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment