6

This question inspired me to ask the following question. Does the DllImport attribute always loads the specific DLL even when you're not calling/using the method.

For example when you have the following code:

static class Program {

    [DllImport("kernel32.dll")]
    static extern bool AllocConsole();

    static void Main()
    {
        if (true)                                
        {
            //do some things, for example starting the service.
        }
        else 
        {
            AllocConsole();
        }           
     }        
 }

Now when the application is started the AllocConsole will never be fired but will the dll be loaded anyway?

Community
  • 1
  • 1
Martijn B
  • 4,065
  • 2
  • 29
  • 41
  • 1
    What happens if you change it to `[DllImport("kernel99.dll")]`? Assuming you don't have one of those of course. If there's no error, I guess it didn't try to load it. – Blorgbeard Jan 26 '12 at 12:21

2 Answers2

4

As the MSDN says:

Locating and loading the DLL, and locating the address of the function in memory occur only on the first call to the function.

But you can easily verify this by specifying an nonexistent dll in the attribute.

Kolja
  • 2,307
  • 15
  • 23
3

I did a little test. The following program runs fine:

static class Program {
    [DllImport("doesnotexist.dll")]
    static extern bool AllocConsole();
    static void Main() {
        if (false) AllocConsole();
    }        
}

The following program raises a DllNotFoundException on the AllocConsole() line.

static class Program {
    [DllImport("doesnotexist.dll")]
    static extern bool AllocConsole();
    static void Main() {
        if (true) AllocConsole();
    }        
}

So it looks like the dll is only loaded when it is first called.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272