title: When exactly are assemblies loaded?
body: <p>So I'm trying to understand exactly when .NET Assemblies are loaded into a .NET process. I read <a href="http://weblog.west-wind.com/posts/2012/Nov/03/Back-to-Basics-When-does-a-NET-Assembly-Dependency-get-loaded" rel="noreferrer">this blog entry</a> which did a great job of explaining things and confirmed a lot of what I thought I already knew, but it also brought up a point in which I think I slightly misunderstood.</p>
  
  <blockquote>
    <p>Dependent Assemblies are just in time loaded when first referenced in
    code</p>
  </blockquote>
  
  <p>I took this to mean that <em>when and furthermore if</em> the first time a call to an assembly was made then the assembly was loaded into the program. So if I have a program like the sample below where the line in which the <code>RasDialer</code> class is instantiated would never be called - I believed that the <code>DotRas</code> assembly would never be loaded into the process and I was definitely wrong about that. </p>
  
  <p>However, if the code is truly unreachable as in my commented out section - then the assembly will never load, but it seems that if there is a chance then the assembly will be loaded. </p>
  
  <p><strong>Here is my little test application:</strong></p>
  
  <pre><code>static void Main(string[] args)
  {
      Console.WriteLine("Before");
      var dictionary = new Dictionary&lt;int, string&gt;();
      PrintAssemblies(); // &lt;- DotRas is loaded here for null check variant
  
      if (dictionary == null)
      {
          // This line will never execute, but it does not matter
          var dialer = new RasDialer();
      }
  
      // DotRas will not be loaded if I uncomment this and comment 
      // out the other if statement since it is truly unreachable
      //if (false)
      //{
      //    var dialer = new RasDialer();
      //}
  
      Console.WriteLine(Environment.NewLine + "After");
      PrintAssemblies();
  
      Console.ReadLine();
  }
  
  public static void PrintAssemblies()
  {
      var assemblies = AppDomain.CurrentDomain.GetAssemblies();
      foreach (var assembly in assemblies)
      {
          Console.WriteLine(assembly.GetName());
      }
  }
  </code></pre>
  
  <p>Is there any easy way to tell when an assembly will be loaded into memory? </p>
  
  <p>In the blog entry that I linked up at the top - his dependent assembly does not load until after his call to <code>PrintAssemblies()</code>, but for mine the dependent assembly loads before the call. So it doesn't appear to be easily predictable. </p>
  
  <p>Am I correct to assume that if there is a chance that a type in the dependent assembly is needed by the JIT compiler it will cause the assembly to be loaded?</p>