Code inspection: Disposal of a variable already captured by the 'using' statement

Last modified: 11 February 2024

If a variable of a type implementing IDisposable is declared in a using statement or with the using declaration, you should not call Dispose() on this variable. Dispose() will be automatically called on the object it contains when the corresponding block is exited. By manually calling Dispose(), you are essentially calling this method twice, which can lead to unexpected behavior or errors.

This inspection reports not only invocations of Dispose() in the using context, but also custom methods that handle resource disposal. Such methods should be marked with the [HandlesResourceDisposalAttribute] from JetBrains.Annotations.