Dispose objects before losing scope

TypeName

DisposeObjectsBeforeLosingScope

CheckId

CA2000

Category

Microsoft.Reliability

Breaking Change

NonBreaking

Cause

A local object of a System.IDisposable type is created but the object is not disposed before all references to the object are out of scope.

Rule Description

If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead.

How to Fix Violations

To fix a violation of this rule, call System.IDisposable.Dispose on the object before all references to it are out of scope.

Note that you can use the using statement (Using in Visual Basic) to wrap objects that implement IDisposable. Objects wrapped in this manner will automatically be disposed at the close of the using block.

When to Exclude Warnings

Do not exclude a warning from this rule, unless you have called a method on your object that calls Dispose, such as Stream.Close

Disposable fields should be disposed

See Also

Reference

Implementing Finalize and Dispose to Clean Up Unmanaged Resources
System.IDisposable