An incorrectly defined platform invoke method (marked with ``++System.Runtime.InteropServices.DllImportAttribute++``) can lead to runtime exceptions because of issues such as a misnamed function, faulty mapping of parameter and return value data types, and incorrect field specifications. If available, it is a lot less error prone, not to mention more secure and quite simpler, to call the equivalent managed method.


This rule raises an issue when a platform invoke method is called and a method with the equivalent functionality exists in the .Net framework library.


== Noncompliant Code Example

----
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace MyLibrary
{
   public class Foo
   {
      public Foo() {}

      [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
      internal static extern int ExpandEnvironmentStrings(
         string lpSrc, StringBuilder lpDst, int nSize);

      public void Bar()
      {
         string environmentVariable = "%TEMP%";
         StringBuilder expandedVariable = new StringBuilder(100);

         ExpandEnvironmentStrings( // Noncompliant
            environmentVariable, 
            expandedVariable, 
            expandedVariable.Capacity);
      }
   }
}
----


== Compliant Solution

----
using System;
using System.Text;

namespace MyLibrary
{
   public class Foo
   {
      public Foo() {}

      public void Bar()
      {
         string environmentVariable = "%TEMP%";
         StringBuilder expandedVariable = new StringBuilder(100);

         Environment.ExpandEnvironmentVariables(environmentVariable);
      }
   }
}
----



ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]
