Code inspection: Return value must be disposed but the method or function is not annotated with [MustDisposeResource]
If you are using the [MustDisposeResourceAttribute] from JetBrains.Annotations to enforce resource disposal in the calling code, and 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. ReSharper reports such cases and suggests annotating the method with [MustDisposeResource]
to explicitly delegate the responsibility of handling the disposable resource to the callers:
[MustDisposeResource]
public class HasNativeResources : IDisposable
{
private IDisposable _resource;
public void Dispose()
{
_resource.Dispose();
}
public void Configure()
{
//configure resource
}
}
public class Test
{
HasNativeResources CreateAndConfigure()
{
var resource = new HasNativeResources();
resource.Configure();
return resource;
}
}
[MustDisposeResource]
public class HasNativeResources : IDisposable
{
private IDisposable _resource;
public void Dispose()
{
_resource.Dispose();
}
public void Configure()
{
//configure resource
}
}
public class Test
{
[MustDisposeResource]
HasNativeResources CreateAndConfigure()
{
var resource = new HasNativeResources();
resource.Configure();
return resource;
}
}
Last modified: 08 May 2024