So I'm trying to understand exactly when .NET Assemblies are loaded into a .NET process. I read this blog entry 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.
Dependent Assemblies are just in time loaded when first referenced in code
I took this to mean that when and furthermore if 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 RasDialer class is instantiated would never be called - I believed that the DotRas assembly would never be loaded into the process and I was definitely wrong about that.
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.
Here is my little test application:
static void Main(string[] args)
{
Console.WriteLine("Before");
var dictionary = new Dictionary<int, string>();
PrintAssemblies(); // <- 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());
}
}
Is there any easy way to tell when an assembly will be loaded into memory?
In the blog entry that I linked up at the top - his dependent assembly does not load until after his call to PrintAssemblies(), but for mine the dependent assembly loads before the call. So it doesn't appear to be easily predictable.
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?