Created
June 19, 2024 09:23
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
/// <summary> | |
/// A <see cref="Dictionary{TKey,TValue}<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<int,string>(); | |
/// Console.WriteLine(x[2]); // prints null | |
/// try { | |
/// Console.WriteLine(((Dictionary<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