Skip to content

IDisposable Implement

"IDisposable" should be implemented correctly

What does this mean ?

The IDisposable interface is a mechanism to release unmanaged resources. This rule raises an issue when the recommended dispose pattern, as defined by Microsoft, is not adhered to.

What can happen ?

If IDisposable interface is not implemented correctly, this could result in resource leaks or more severe bugs.

Recommendation

  • Recursion in type inheritance should not be used.
  • If a base class implements IDisposable your class should not have IDisposable in the list of its interfaces. In such cases it is recommended to override the base class's protected virtual void Dispose(bool) method or its equivalent.
  • The class should not implement IDisposable explicitly, e.g. the Dispose() method should be public.
  • The class should contain protected virtual void Dispose(bool) method. This method allows the derived classes to correctly dispose the resources of this class.
  • The content of the Dispose() method should be invocation of Dispose(true) followed by GC.SuppressFinalize(this)
  • If the class has a finalizer, i.e. a destructor, the only code in its body should be a single invocation of Dispose(false).
  • If the class inherits from a class that implements IDisposable it must call the Dispose, or Dispose(bool) method of the base class from within its own implementation of Dispose or Dispose(bool), respectively. This ensures that all resources from the base class are properly released.

Sample Code

Vulnerable :

using System;

class ExampleClass
{
    public void ExampleMethod(Random random)
    {
        var sensitiveVariable = random.Next();
    }
}

Non Vulnerable :

using System;
using System.Security.Cryptography;

class ExampleClass
{
    public void ExampleMethod(RandomNumberGenerator randomNumberGenerator, int toExclusive)
    {
        var sensitiveVariable = randomNumberGenerator.GetInt32(toExclusive);
    }
}

References :