Export (0) Print
Expand All

Dispose objects before losing scope

TypeName

DisposeObjectsBeforeLosingScope

CheckId

CA2000

Category

Microsoft.Reliability

Breaking Change

NonBreaking

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.

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.

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.

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

Community Additions

ADD
Show:
© 2015 Microsoft