Should I use Declare or DllImport in VB.NET? What's the difference?
Written: 6/19/2002 Updated: 6/19/2002
The Declare statement exposes a subset of the functionality of the DllImport attribute, and implies different marshaling behavior for parameters to make functions behave in a way familiar to VB6 developers.
Using a Declare statement gives you the same code as if the DllImport attribute is used with CallingConvention.Winapi, ExactSpelling=True and SetLastError=True. Adding an Alias clause has the same effect as using DllImport's EntryPoint property. Declare also supports using a Ansi/Auto/Unicode modifier that maps directly to the corresponding CharSet option. Using the Auto modifier also changes ExactSpelling to False.
String parameters gets special marshaling attributes when used in Declare statements. When passed ByVal, they are always treated as UnmanagedType.VBByRefStr, and the parameter is actually changed to be ByRef under the hood to enable changes to the string to be retrieved back. When declared as ByRef, the marshaling setting is one of UnmanagedType.AnsiBStr, UnmanagedType.TBStr or UnmanagedType.BStr, depending on which, if any, charset modifier is used. These implied marshaling settings can always be overridden by applying the MarshalAs attribute to the parameter. Return value Strings don't get any special marshaling set, neither does String arrays.
So Declare statements will do in most situations. The only time you really need to use the DllImport attribute on a regular Shared method is when you want to set the calling convention to something other than Winapi, set SetLastError=False or PreserveSig=False. Other than that, it's mostly a matter of personal preference.