csharplang icon indicating copy to clipboard operation
csharplang copied to clipboard

Bug in control flow analysis for out arguments (VS 16.8, .NET 5)

Open rameel opened this issue 6 years ago • 3 comments

Looks like the C# compiler have a bug in control flow analysis

// Project1.csproj
using Library;

namespace ControlFlowError
{
    public sealed class ValueProvider
    {
        public bool TryGetValue(out Result result)
        {
            // Expected: The out parameter 'result' must be assigned to before control leaves the current method
            return false;
        }
    }
}
// Project2.csproj
namespace Library
{
    public readonly struct Result
    {
        public object Value { get; }

        //public readonly object Value; // 2. Works as expected
        //public readonly int Value;    // 3. Works as expected
    }
}

Steps to Reproduce: Clone the project https://github.com/rameel/ControlFlowError

Expected Behavior: Compilation error with the message: The out parameter 'result' must be assigned to before control leaves the current method

Actual Behavior: Compiled successfully

rameel avatar Feb 11 '19 11:02 rameel

This is by design (the struct has no accessible fields), but I believe we want to change the design.

gafter avatar Mar 26 '19 17:03 gafter

Ah, got it

rameel avatar Mar 26 '19 19:03 rameel

Also reported at https://github.com/dotnet/roslyn/issues/39062 and many other places.

gafter avatar May 09 '20 14:05 gafter