Beef icon indicating copy to clipboard operation
Beef copied to clipboard

False positive on unassigned out parameter

Open Grimelios opened this issue 10 months ago • 1 comments

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;
        }
    }
}

Grimelios avatar Feb 15 '25 05:02 Grimelios

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;
        }
    }
}

m910q avatar Mar 08 '25 17:03 m910q