CA2000 When returning the disposable object (using a try/finally block)

64 views Asked by At

In C#, we are trying to properly handle the disposition of an object in a method that returns it (or rather, it sets it as another object's property and returns the other object). Following what the docs state, the error CA2000 still jumps.

We tried using the try/finally statement as it is displayed in the C# documentation: https://github.com/dotnet/docs/blob/main/docs/fundamentals/code-analysis/quality-rules/ca2000.md Example:

public static ApiRequestData Method(ApiRequestData request, byte[] contents)
{
    var content = (HttpContent)request.Content;

    ByteArrayContent byteArrayContent = null;
    try 
    { 
        byteArrayContent = new ByteArrayContent(contents);
    
        byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("text/plain; charset=iso-8859-5");
        content.Add(byteArrayContent, "fieldName", "fileName");
        byteArrayContent = null;
    }
    finally
    {
        byteArrayContent?.Dispose();
    }

    return request;
}

We also tried returning inside the try block, but unless we remove the byteArrayContent = null;, CA2000 jumps. Another thing we tried is removing the byteArrayContent = null; block and changing the finally clause to a catch clause, but CA2000 still jumps.

Is it a false positive, are we doing something wrong? What should we be doing? Thanks in advance!

0

There are 0 answers