== Why is this an issue?

Usually ``++IntPtr++`` and ``++UIntPtr++`` fields are used to store pointers to unmanaged resources and the finalizer will free the unmanaged resource pointed to by the pointer fields. If the garbage collector finalises the object while the managed resources are still in use it could lead to serious, hard to diagnose bug. To prevent this from happening the object should be kept alive by calling ``++GC.KeepAlive(this)++`` in methods calling unmanaged code on this pointers.


=== Noncompliant code example

[source,csharp]
----
using System;

namespace MyLibrary
{
   class Foo
   {
      private IntPtr res;

      Foo()
      {
         GetRes (res);
      }

      ~Foo()
      {
         FreeRes (res);
      }

      void Bar()  // Noncompliant
      {
         UseRes(res); 
      }

      // Methods that would typically make calls to unmanaged code.
      void GetRes(IntPtr p)
      {
        // Allocate the resource ...
      }
      void FreeRes(IntPtr p)
      {
        // Free the resource and set the pointer to null ...
      }
      void UseRes(IntPtr p)
      {
        // Use the resource in unmanaged code ...
      }

   }
}
----


=== Compliant solution

[source,csharp]
----
using System;

namespace MyLibrary
{
   class Foo
   {
      private IntPtr res;

      Foo()
      {
         GetRes (res);
      }

      ~Foo()
      {
         FreeRes (res);
      }

      void Bar()
      {
         UseRes(res); 
         GC.KeepAlive(this);
      }

      // Methods that would typically make calls to unmanaged code.
      void GetRes(IntPtr p)
      {
        // Allocate the resource ...
      }
      void FreeRes(IntPtr p)
      {
        // Free the resource and set the pointer to null ...
      }
      void UseRes(IntPtr p)
      {
        // Use the resource in unmanaged code ...
      }

   }
}
----


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

=== on 28 Jan 2019, 14:34:46 Amaury Levé wrote:
We cannot find how to get the original FxCop to report any issue + the description is not precise enough so we cannot find what/how the rule should be implemented.


cc [~nicolas.harraudeau]

endif::env-github,rspecator-view[]
