title: What's the best way to ensure a base class's static constructor is called?
body: <p>The <a href="http://msdn.microsoft.com/en-us/library/k9x6w0hc%28v=vs.80%29.aspx" rel="noreferrer">documentation on static constructors in C#</a> says:</p>
  
  <blockquote>
    <p>A static constructor is used to
    initialize any static data, or to
    perform a particular action that needs
    performed once only. It is called
    automatically <strong>before the first
    instance is created or any static
    members are referenced</strong>.</p>
  </blockquote>
  
  <p>That last part (about when it is automatically called) threw me for a loop; until reading that part I <em>thought</em> that by simply accessing a class <em>in any way</em>, I could be sure that its base class's static constructor had been called. Testing and examining the documentation have revealed that this is not the case; it seems that the static constructor for a <em>base</em> class is not guaranteed to run until a member <em>of that base class specifically</em> is accessed.</p>
  
  <p>Now, I guess in most cases when you're dealing with a derived class, you would construct an instance and this would constitute an instance of the base class being created, thus the static constructor would be called. But if I'm only dealing with <em>static</em> members of the <em>derived</em> class, what then?</p>
  
  <p>To make this a bit more concrete, I <strong>thought</strong> that the code below would work:</p>
  
  <pre><code>abstract class TypeBase
  {
      static TypeBase()
      {
          Type&lt;int&gt;.Name = "int";
          Type&lt;long&gt;.Name = "long";
          Type&lt;double&gt;.Name = "double";
      }
  }
  
  class Type&lt;T&gt; : TypeBase
  {
      public static string Name { get; internal set; }
  }
  
  class Program
  {
      Console.WriteLine(Type&lt;int&gt;.Name);
  }
  </code></pre>
  
  <p>I assumed that accessing the <code>Type&lt;T&gt;</code> class would automatically invoke the static constructor for <code>TypeBase</code>; but this appears not to be the case. <code>Type&lt;int&gt;.Name</code> is <code>null</code>, and the code above outputs the empty string.</p>
  
  <p>Aside from creating some dummy member (like a static <code>Initialize()</code> method that does nothing), <strong>is there a better way to ensure that a base type's static constructor will be called before any of its derived types is used?</strong></p>
  
  <p>If not, then... dummy member it is!</p>