All rules
CA1417Portability and interoperability Enabled by default: As warning

Do not use OutAttribute on string parameters for P/Invokes

Do not use OutAttribute on string parameters for P/Invokes

Microsoft docs

Description

The .NET runtime automatically performs string interning. If an interned string marked with System.Runtime.InteropServices.OutAttribute is passed by value to a P/Invoke, the runtime can be destabilized.

Cause

A P/Invoke string parameter is passed by value and marked with System.Runtime.InteropServices.OutAttribute.

How to fix violations

If marshalling of modified string data back to the caller is required, pass the string by reference instead. Otherwise, the System.Runtime.InteropServices.OutAttribute can be removed without any other changes.

Example

 // Violation
[DllImport("MyLibrary")]
private static extern void Foo([Out] string s);

// Fixed: passed by reference
[DllImport("MyLibrary")]
private static extern void Foo(out string s);

// Fixed: marshalling data back to caller is not required
[DllImport("MyLibrary")]
private static extern void Foo(string s);

When to suppress

It is not safe to suppress a warning from this rule.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0