Move pinvokes to native methods class

TypeName

MovePInvokesToNativeMethodsClass

CheckId

CA1060

Category

Microsoft.Design

Breaking Change

Breaking

Cause

A method uses Platform Invocation Services to access unmanaged code and is not a member of one of the 'NativeMethods' classes.

Rule Description

Platform Invocation methods, such as those marked with the System.Runtime.InteropServices.DllImportAttribute attribute, or methods defined by using the Declare keyword in Visual Basic, access unmanaged code. These methods should be in one of the following classes:

  • NativeMethods - This class does not suppress stack walks for unmanaged code permission. (System.Security.SuppressUnmanagedCodeSecurityAttribute must not be applied to this class.) This class is for methods that can be used anywhere because a stack walk will be performed.

  • SafeNativeMethods - This class suppresses stack walks for unmanaged code permission. (System.Security.SuppressUnmanagedCodeSecurityAttribute is applied to this class.) This class is for methods that are safe for anyone to call. Callers of these methods are not required to do a full security review to ensure that the usage is secure because the methods are harmless for any caller.

  • UnsafeNativeMethods - This class suppresses stack walks for unmanaged code permission. (System.Security.SuppressUnmanagedCodeSecurityAttribute is applied to this class.) This class is for methods that are potentially dangerous. Any caller of these methods must do a full security review to ensure that the usage is secure because no stack walk will be performed.

These classes are declared as internal (Friend, in Visual Basic), and declare a private constructor to prevent new instances from being created. The methods in these classes should be static and internal (Shared and Friend in Visual Basic).

How to Fix Violations

To fix a violation of this rule, move the method to the appropriate NativeMethods class.

When to Exclude Warnings

Do not exclude a warning from this rule.

Example

The following example declares a method that violates this rule.

Imports System

NameSpace MSInternalLibrary

' Violates rule: MovePInvokesToNativeMethodsClass.
Friend Class UnmanagedApi
    Friend Declare Function RemoveDirectory Lib "kernel32" ( _
       ByVal Name As String) As Boolean
End Class

End NameSpace 
using System;
using System.Runtime.InteropServices;

namespace DesignLibrary
{
// Violates rule: MovePInvokesToNativeMethodsClass.
    internal class UnmanagedApi
    {
        [DllImport("kernel32.dll")]
        internal static extern bool RemoveDirectory(string name);
    }
}