Code inspection: Disposal of a variable already captured by the 'using' statement
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.
using (var disposable = new MyDisposable())
{
// Warning
disposable.Dispose();
}
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.
class DisposalSample
{
void HandleDisposal(
[HandlesResourceDisposal] MyDisposable resource)
{
// Custom disposal implementation
}
void Test()
{
using (var disposable = new MyDisposable())
{
// Warning
HandleDisposal(disposable);
}
}
}
Last modified: 11 February 2024