Dispose objects before losing scope
Dispose IDisposable objects before they go out of scope.
Microsoft docsDescription
Objects implementing IDisposable should be disposed before all references to them go out of scope.
Cause
A local object of an System.IDisposable type is created, but the object is not disposed before all references to the object are out of scope.
By default, this rule analyzes the entire codebase, but this is configurable.
Why it matters
Failing to dispose can leak unmanaged resources such as file handles and sockets.
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.
You can use the using statement (Using in Visual Basic) to wrap objects that implement System.IDisposable. Objects that are wrapped in this manner are automatically disposed at the end of the using block. However, the following situations should not or cannot be handled with a using statement:
- To return a disposable object, the object must be constructed in a
try/finallyblock outside of ausingblock.
- Do not initialize members of a disposable object in the constructor of a
usingstatement.
- When constructors that are protected by only one exception handler are nested in the acquisition part of a
usingstatement, a failure in the outer constructor can result in the object created by the nested constructor never being closed. In the following example, a failure in the System.IO.StreamReader constructor can result in the System.IO.FileStream object never being closed. CA2000 flags a violation of the rule in this case.
- Dynamic objects should use a shadow object to implement the dispose pattern of System.IDisposable objects.
Examples
var stream = new FileStream(path, FileMode.Open);
Return(stream.Length);using var stream = new FileStream(path, FileMode.Open);
Return(stream.Length);When to suppress
Do not suppress a warning from this rule unless:
- You've called a method on your object that calls
Dispose, such as System.IO.Stream.Close. - The method that raised the warning returns an System.IDisposable object that wraps your object.
- The allocating method does not have dispose ownership; that is, the responsibility to dispose the object is transferred to another object or wrapper that's created in the method and returned to the caller.