Skip to content
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

False positive on unassigned out parameter #2138

Open
Grimelios opened this issue Feb 15, 2025 · 1 comment
Open

False positive on unassigned out parameter #2138

Grimelios opened this issue Feb 15, 2025 · 1 comment

Comments

@Grimelios
Copy link

namespace Scratch
{
    static
    {
        // Error! ("The out parameter `out` must be assigned to before control leaves the current method")
        private static bool A(int value, out int @out)
        {
            switch (value)
            {
                default: return B(out @out);
            }
        }
        
        private static bool B(out int @out)
        {
            @out = 123;

            return true;
        }
    }
}

The code above fails to compile with the message The out parameter 'out' must be assigned to before control leaves the current method. This error is a false positive since @out is guaranteed to be assigned. Modifying the two functions to return void (shown below) compiles successfully:

namespace Scratch
{
    static
    {
        // No error!
        private static void A(int value, out int @out)
        {
            switch (value)
            {
                default: B(out @out);
            }
        }
        
        private static void B(out int @out)
        {
            @out = 123;
        }
    }
}

Here's one additional example that's functionally identical to the first example, but compiles successfully:

namespace Scratch
{
    static
    {
        // No error!
        private static bool A(int value, out int @out)
        {
            switch (value)
            {
                default:
                {
                    B(out @out);

                    return true;
                }
            }
        }
        
        private static void B(out int @out)
        {
            @out = 123;
        }
    }
}
@m910q
Copy link
Contributor

m910q commented Mar 8, 2025

I have run into a similar issue.
It only happens when the code is inside a switch case.

static class Program
{
    static void Test(out int output)
    {
        switch (1)
        {
            default:
                if (false)
                {
                    output = 1;
                    return;
                }
                else
                {
                    //output = 1; // Works if this is enabled
                }

                output = 1;
                return;
        }
    }
}

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

No branches or pull requests

2 participants