C#idiomatic C#
ca1420fundamentals/code-analysis/quality-rules

Code analysis

CA1420: Property, type, or attribute requires runtime marshalling

Learn about code analysis rule CA1420: Property, type, or attribute requires runtime marshalling

CA1420 Interoperability enabled by default in .NET 10: As warning
Fix is breaking or non-breaking BreakingApplicable languages C# and Visual Basic

Cause

A code feature is used that requires runtime marshalling, and runtime marshalling is explicitly disabled.

Rule description

Using features that require runtime marshalling when runtime marshalling is disabled will result in runtime exceptions.

How to fix violations

Enable runtime marshalling or remove the code that requires runtime marshalling.

When to suppress warnings

Don't suppress a warning from this rule.

Example

The following code snippet shows a violation of CA1420:

sample · csharpdocs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1420.cs

csharp
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: DisableRuntimeMarshalling]

class C
{
    // Violates rule CA1420.
    [DllImport("NativeLibrary", SetLastError = true)]
    public static extern void MyMethod();
}

sample · vbdocs/fundamentals/code-analysis/quality-rules/snippets/vb/all-rules/ca1420.vb

vb
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices

<Assembly: DisableRuntimeMarshalling>

Class C
    ' Violates rule CA1420.
    <DllImport("NativeLibrary", SetLastError:=True)>
    Public Shared Sub MyMethod()
        '...
    End Sub
End Class

To fix the violation, remove the System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute on the assembly.