ReSharper
 
Get ReSharper
Get your hands on the new features ahead of the release by joining the Early Access Program for ReSharper 2025.1! Learn more

Dispose analysis

Last modified: 25 September 2024

To reduce the number of resource leaks in your code and improve its performance, you need to ensure the correct handling of disposable resources. On the one hand, you want to enforce the using keyword at call sites of the specific APIs, but on the other hand, you don't want to have a lot of noise with false positives around each usage of IDisposable.

Therefore, to analyze the handling of disposable resources, ReSharper relies on a set of annotation attributes from JetBrains.Annotations.

To start the analysis, annotate your critical disposable APIs with the [MustDisposeResource] attribute. You can use this attribute to annotate disposable types, their constructors, and factory methods. Once this is done, ReSharper will report call sites that are not treating the resource as disposable and suggest the corresponding quick-fixes:

ReSharper: Dispose analysis. Enforce 'using' directive

The warning will disappear as soon as you wrap the disposable resource in a using or explicitly call Dispose() on that resource.

As you can see on the screenshot above, usages of the [MustDisposeResource] are also marked with the corresponding inlay hints, which are configurable on the Environment | Inlay Hints | C# | Other page of ReSharper options Alt+R, O.

If your API does not expose the Dispose() method or have several methods that handle the disposal, you can annotate those methods that actually dispose resources with the [HandlesResourceDisposal] attribute:

If a custom dispose method expects a disposable resource as an argument, you can annotate the corresponding parameter with [HandlesResourceDisposal]:

Finally, if a method that obtains a resource from an annotated source does not handle resource disposal, but returns it to other callers, the problem of potential incorrect handling of the resource is passed to the callers. If this is deliberate, you can let the analyzer know that by annotating the method with [MustDisposeResource] to explicitly delegate the responsibility of handling the disposable resource to the callers: