DllImportAttribute.SetLastError Field

Definition

Indicates whether the callee sets an error (SetLastError on Windows or errno on other platforms) before returning from the attributed method.

C#
public bool SetLastError;

Field Value

Examples

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.

C#
internal static class NativeMethods
{
    [DllImport("user32.dll", SetLastError = true)]
    internal static extern int MessageBoxA(
        IntPtr hWnd, string lpText, string lpCaption, uint uType);
}

Remarks

true to indicate that the callee will set an error via SetLastError on Windows or errno on other platforms; otherwise, false. The default is false.

If this field is set to true, the runtime marshaler calls GetLastError or errno and caches the value returned to prevent it from being overwritten by other API calls. You can retrieve the error code by calling GetLastPInvokeError on .NET 6.0 and above or GetLastWin32Error on .NET 5 and below or .NET Framework.

On .NET, the error information is cleared (set to 0) before invoking the callee when this field is set to true. On .NET Framework, the error information is not cleared. This means that error information returned by GetLastPInvokeError and GetLastWin32Error on .NET represents only the error information from the last p/invoke with DllImportAttribute.SetLastError set to true. On .NET Framework, the error information can persist from one p/invoke to the next.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

See also