Note that there are some explanatory texts on larger screens.

plurals
  1. PODictionary with null key?
    primarykey
    data
    text
    <p>Firstly, <em>why</em> doesn't <code>Dictionary&lt;TKey, TValue&gt;</code> support a single null key?</p> <p>Secondly, is there an existing dictionary-like collection that does?</p> <p>I want to store an "empty" or "missing" or "default" <code>System.Type</code>, thought <code>null</code> would work well for this.</p> <hr> <p>More specifically, I've written this class:</p> <pre><code>class Switch { private Dictionary&lt;Type, Action&lt;object&gt;&gt; _dict; public Switch(params KeyValuePair&lt;Type, Action&lt;object&gt;&gt;[] cases) { _dict = new Dictionary&lt;Type, Action&lt;object&gt;&gt;(cases.Length); foreach (var entry in cases) _dict.Add(entry.Key, entry.Value); } public void Execute(object obj) { var type = obj.GetType(); if (_dict.ContainsKey(type)) _dict[type](obj); } public static void Execute(object obj, params KeyValuePair&lt;Type, Action&lt;object&gt;&gt;[] cases) { var type = obj.GetType(); foreach (var entry in cases) { if (entry.Key == null || type.IsAssignableFrom(entry.Key)) { entry.Value(obj); break; } } } public static KeyValuePair&lt;Type, Action&lt;object&gt;&gt; Case&lt;T&gt;(Action action) { return new KeyValuePair&lt;Type, Action&lt;object&gt;&gt;(typeof(T), x =&gt; action()); } public static KeyValuePair&lt;Type, Action&lt;object&gt;&gt; Case&lt;T&gt;(Action&lt;T&gt; action) { return new KeyValuePair&lt;Type, Action&lt;object&gt;&gt;(typeof(T), x =&gt; action((T)x)); } public static KeyValuePair&lt;Type, Action&lt;object&gt;&gt; Default(Action action) { return new KeyValuePair&lt;Type, Action&lt;object&gt;&gt;(null, x =&gt; action()); } } </code></pre> <p>For switching on types. There are two ways to use it:</p> <ol> <li>Statically. Just call <code>Switch.Execute(yourObject, Switch.Case&lt;YourType&gt;(x =&gt; x.Action()))</code></li> <li>Precompiled. Create a switch, and then use it later with <code>switchInstance.Execute(yourObject)</code></li> </ol> <p>Works great <em>except</em> when you try to add a default case to the "precompiled" version (null argument exception).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload