This topic has not yet been rated - Rate this topic

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

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
False Positive
This rule doesn't recognize all situations where a disposable resource is not owned by the thread. Examples being a StringReader embedded within an XmlReader, or assigning a new Font object to a WinForms control's Font property.
False Positive
This can occur when one is creating and showing a form in a method.