Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the DllImport attribute always loading the unmanaged DLL

Tags:

c#

.net

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?

like image 917
Martijn B Avatar asked Jan 26 '12 11:01

Martijn B


1 Answers

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.

like image 200
Kolja Avatar answered Nov 15 '22 07:11

Kolja