Skip to content

LGTM.com - false positive - cs/useless-assignment-to-local when assigned as an out within a try/finally block  #2752

Open
@ahsonkhan

Description

@ahsonkhan

Description of the false positive

In general, the cs/useless-assignment-to-local rule makes sense: https://lgtm.com/rules/1506093386171/

However, in some cases, the error results in a false positive, where the compiler would throw if the assignment was removed. This happens if the local is assigned within a try/finally block (say, by a method call returning an out), and then used in the finally block. If the method call throws an exception, the local could be left uninitialized.

Here's a simplified example:

private void Test()
{
    ArraySegment<byte> rented = default; // necessary, otherwise compiler complains

    try
    {
        MethodThatMightThrow(out rented);
    }
    finally
    {
        DoSomething(rented);
    }
}

private void MethodThatMightThrow(out ArraySegment<Byte> rented)
{
    //rented = default;
    throw new InvalidOperationException();
}

private int DoSomething(ArraySegment<Byte> rented)
{
    return rented.Array.Length; // null ref if rented isn't assigned.
}

URL to the alert on the project page on LGTM.com

https://lgtm.com/projects/g/dotnet/corefx/latest/files/src/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs?sort=name&dir=ASC&mode=heatmap#V898

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions