All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S4002.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

This rule raises an issue when a disposable type contains fields of the following types and does not implement a finalizer:

  • System.IntPtr
  • System.UIntPtr
  • System.Runtime.InteropService.HandleRef

Noncompliant code example

using System;
using System.Runtime.InteropServices;

namespace MyLibrary
{
  public class Foo : IDisposable // Noncompliant: Doesn't have a finalizer
  {
    private IntPtr myResource;
    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
      if (!disposed)
      {
        // Dispose of resources held by this instance.
        FreeResource(myResource);
        disposed = true;

        // Suppress finalization of this disposed instance.
        if (disposing)
        {
          GC.SuppressFinalize(this);
        }
      }
    }

    public void Dispose() {
      Dispose(true);
    }
  }
}

Compliant solution

using System;
using System.Runtime.InteropServices;

namespace MyLibrary
{
  public class Foo : IDisposable
  {
    private IntPtr myResource;
    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
      if (!disposed)
      {
        // Dispose of resources held by this instance.
        FreeResource(myResource);
        disposed = true;

        // Suppress finalization of this disposed instance.
        if (disposing)
        {
          GC.SuppressFinalize(this);
        }
      }
    }

    ~Foo()
    {
      Dispose(false);
    }
  }
}

Resources

  • Related: {rule:csharpsquid:S3881} - "IDisposable" should be implemented correctly




© 2015 - 2024 Weber Informatics LLC | Privacy Policy