Skip to content

IDisposable Implement

"IDisposable" should be properly implemented.

What does this mean ?

The IDisposable interface is used to dispose of unmanaged resources. This rule becomes problematic when the suggested disposal pattern, as described by Microsoft, is not followed.

What can happen ?

If the IDisposable interface is not implemented appropriately, resource leaks or more serious issues may occur.

Recommendation

  • In type inheritance, recursion should be avoided.
  • 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.
  • If a base class implements IDisposable, your class should not include IDisposable in its interface list. In such circumstances, it is advised to override the protected virtual void Dispose(bool) function or its equivalent in the base class.
  • The protected virtual void Dispose(bool) function should be included in the class. This function allows derived classes to properly dispose of this class's resources.
  • The Dispose() method's payload should be a call of Dispose(true) followed by GC. SuppressFinalize(this)
  • If the class has a finalizer, also known as a destructor, the only code in its body should be a single call to Dispose (false).
  • If the class inherits from a class that implements IDisposable, it must invoke the base class's Dispose or Dispose(bool) function from inside its own implementation of Dispose or Dispose(bool). This guarantees that all base class resources are correctly removed.

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