Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
ahsonkhan opened this issue Feb 4, 2020 · 1 comment

Comments

@ahsonkhan
Copy link

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

@ahsonkhan ahsonkhan changed the title LGTM.com - false positive - cs/useless-assignment-to-local when assigned within a try/finally block LGTM.com - false positive - cs/useless-assignment-to-local when assigned as an out within a try/finally block Feb 4, 2020
@hvitved hvitved added the C# label Feb 4, 2020
@calumgrant
Copy link
Contributor

Many thanks for your report. We will work on a fix for this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants