title: Base class to hold collection instances of derived classes
body: <p>I have a bunch of classes in my C# program that contain a  static member, which is a dictionary collection of all instances of that class - something like this:</p>
  
  <pre><code>class A
  {
    private static Dictionary&lt;int,A&gt; dict = new Dictionary&lt;int, A&gt;();
    public static A GetInstance(int handle) { return dict[handle];}
  
    public A(int handle) {this._handle = handle; dict[handle] = this;}
    ~A() { dict.Remove(_handle);}
    private int _handle;
  
  }
  </code></pre>
  
  <p>I've got this duplicated in a number of classes, and would like to factor out this common code, but can't figure out how do this. Putting it into a plain base class does not work, as I want a new collection for each concrete class. I sense there must be a way to do it with generics, but I can't quite see how at the moment.</p>
  
  <p>For example, this is not right:</p>
  
  <pre><code>abstract class Base&lt;T&gt;
  {
    private static Dictionary&lt;int,T&gt; dict = new Dictionary&lt;int, T&gt;();
    public static T GetInstance(int handle) { return dict[handle];}
  
    public A(int handle) {this._handle = handle; dict[handle] = this;}
    ~Base() { dict.Remove(_handle);}
    private int _handle;
  }
  
  class A : Base&lt;A&gt;
  {
  }
  </code></pre>
  
  <p>It fails to complile as the constructor of A is not right. Am I missing a trick here?</p>