Be consistent with DllImports

Fri, December 14, 2007, 01:37 AM under dotNET
Most .NET developers have at some point in their career called into a native library (whether it was C\C++ DLL part of the Windows OS or one of their own or one from a 3rd party is irrelevant). To call native functions form .NET you use the DLLImport attribute and even though it has various overloads, the main thing we do is point it to the native DLL name (the Declare statement in VB does the same thing although I use DllImport in VB projects as well).

The subtle point is that there is no convention for how we specify the name so, for example, all of the following are valid and will work at runtime:
    [DllImport("kernel32.dll")]
static extern ...;
[DllImport("kernel32")]
static extern ...;
[DllImport("Kernel32.DLL")]
static extern ...;
[DllImport("KERNEL32")]
static extern ...;
[DllImport("KeRnEl32.DlL")]
static extern ...;
Now, I know that there is no convention, but if you used the above this is what you would see in ILDASM (and indeed in reflector too):


You may think: "So what, isn't just one kernel32 loaded in my process at the end of the day?". Well, yes, but there is a slight performance penalty because the loader treats each separate string as a separate module!

Some of you are thinking that "for that performance reason alone" you should standardize on a convention e.g. always use lowercase and include the ".dll" extension... or something like that. Others are probably thinking that "the performance gains are negligible" for you to make a rule for this.

In my opinion (and it is my blog so don't be shocked that these are my opinions here!), you are both wrong and right at the same time. For me, this is an issue of hygiene. Once I learnt about this fact (many moons ago :-), I couldn't live with myself if in my assemblies I didn't define a standard for pinvoking. Nothing to do with performance – it just feels dirty to me not to use the same DLL name throughout my assembly. That's just the kind of person I am...

So I sighed when I discovered that System.Core.dll is the first and only assembly so far in v2.0/3.0/3.5 of the framework not to follow the "all lower case with .dll appended" convention, as viewing it through a disassembler proves :-(