Methods marked with the System.Runtime.InteropServices.DllImportAttribute
attribute use Platform Invocation Services to access
unmanaged code and should not be exposed. Keeping them private or internal makes sure that their access is controlled and properly managed.
This rule raises an issue when a method declared with DllImport
is public or protected.
Noncompliant code example
using System;
using System.Runtime.InteropServices;
namespace MyLibrary
{
public class Foo
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
public static extern bool RemoveDirectory(string name); // Noncompliant
}
}
Compliant solution
using System;
using System.Runtime.InteropServices;
namespace MyLibrary
{
public class Foo
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern bool RemoveDirectory(string name);
}
}