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

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

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

IDisposable is an interface implemented by all types which need to provide a mechanism for releasing unmanaged resources.

Unlike managed memory, which is taken care of by the garbage collection,

The interface declares a Dispose method, which the implementer has to define.

The method name Dispose should be used exclusively to implement IDisposable.Dispose to prevent any confusion.

It may be tempting to create a Dispose method for other purposes, but doing so will result in confusion and likely lead to problems in production.

Exceptions

Methods named Dispose and invoked from the IDisposable.Dispose implementation are not reported.

public class GarbageDisposal : IDisposable
{
  protected virtual void Dispose(bool disposing)
  {
    //...
  }
  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }
}

How to fix it

First, it is important to determine whether instances of the type defining the Dispose method should support the IDisposable interface or not.

The decision would be based on whether the instance can have unmanaged resources which have to be dealt with, upon destruction or earlier in the lifetime of the object.

The Dispose pattern can help to take the decision.

If the type should not support the pattern, the Dispose method should be renamed to something which is different than Dispose, but still relevant and possibly more specific to the context.

Code examples

Noncompliant code example

public class GarbageDisposal
{
  private int Dispose()  // Noncompliant
  {
    // ...
  }
}

Compliant solution

public class GarbageDisposal : IDisposable
{
  public void Dispose()
  {
    // ...
  }
}

or

public class GarbageDisposal
{
  private int Grind()
  {
    // ...
  }
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy