DllImportAttribute.SetLastError DllImportAttribute.SetLastError DllImportAttribute.SetLastError DllImportAttribute.SetLastError Field


Indicates whether the callee calls the SetLastError Windows API function before returning from the attributed method.

public: bool SetLastError;
public bool SetLastError;
val mutable SetLastError : bool
Public SetLastError As Boolean 

Field Value


In some cases, Visual Basic developers use the DllImportAttribute, instead of using the Declare statement, to define a DLL function in managed code. Setting the SetLastError field is one of those cases.

[DllImport("user32.dll", SetLastError=true)]
int MessageBoxA(IntPtr hWnd, String^ Text,
                String^ Caption, unsigned int Type);
internal static class NativeMethods
    [DllImport("user32.dll", SetLastError = true)]
    internal static extern int MessageBoxA(
        IntPtr hWnd, string lpText, string lpCaption, uint uType);
Friend Class NativeMethods
    <DllImport("user32.dll", SetLastError:=True)>
    Friend Shared Function MessageBoxA(hWnd As IntPtr, lpText As String,
        lpCaption As String, uType As UInteger) As Integer
    End Function
End Class


true to indicate that the callee will call SetLastError; otherwise, false. The default is false.

The runtime marshaler calls GetLastError and caches the value returned to prevent it from being overwritten by other API calls. You can retrieve the error code by calling GetLastWin32Error.

Applies to

See also