Code inspection: Return value of a property must be disposed by the callee
If you are using the [MustDisposeResourceAttribute] from JetBrains.Annotations to enforce resource disposal in the calling code, ReSharper reports properties that directly return a resource from an annotated source. This means that users of the API must handle a disposable resource that is created each time they use the property. Here is an example:
[MustDisposeResource]
public class HasNativeResources : IDisposable
{
private IDisposable _resource;
public void DoTaskOne() {/*do something with _resource*/}
public void DoTaskTwo() {/*do something with _resource*/}
public void Dispose() => _resource.Dispose();
}
public class Item
{
// The potential problem is reported here
public HasNativeResources Resource => new HasNativeResources();
}
public class Test
{
public Test()
{
var item = new Item();
// Resource leak can happen here if the resource is not properly handled
item.Resource.DoTaskOne();
item.Resource.DoTaskTwo();
}
}
There are two general ways to fix this problem:
Communicate to the API users that the property is not a part of the object. This can be done, for example, by converting the property to a method.
Make the property a part of the object and handle the resource internally. This can be done, for example, by adding a backing field for the property and disposing it in the object's
Dispose()
method.
Last modified: 11 February 2024