dotnet/roslyn

C#: The compiler may incorrectly handle the null-conditional operator in .NET Framework 2.0, 3.0, 3.5 (works fine with 4.0+)

開放

#45,165 建立於 2020年6月14日

 (3 則留言) (1 個反應) (1 位負責人)C# (4,257 個分叉)batch import
Area-InteractiveBugInteractive-Debugginghelp wanted

倉庫指標

星標
 (20,414 顆星)
PR 合併指標
 (平均合併 6天 17小時) (30 天內合併 256 個 PR)

描述

Version Used: VS 15.9.24

Steps to Reproduce: Create a classic desktop console project using .Net Framework 2.0, 3.0 or 3.5.

Have the following code:

class Program
{
    static void Main()
    {
        var b = new BClass { Prop = new object() };
        new AClass(b);
    }
}

public class AClass
{
    BClass bClass;

    public AClass(BClass b)
    {
        bClass = b;

        var a1 = bClass;       // not null
        var a2 = bClass.Prop;  // not null
        var a3 = b?.Prop;      // not null
        var a4 = bClass?.Prop; // null, WHY???

        ; // set break point to here
    }
}
public class BClass
{
    public object Prop { get; set; }
}

Set the breakpoint on the empty line as instructed in the code. Run.

Expected Behavior: Variable a4 is not null.

Actual Behavior: Variable a4 is null.

Additional information:

  • Adding other code may trigger a4 to become non null later than it should have. E.g. if you have:
var a4 = bClass?.Prop; // null, WHY???

Console.WriteLine(a4);  // Set breakpoint here

, then a4 will display as null at the point of having hit the breakpoint at the WriteLine, but it will write "System.Object" in the console as if it is not null. And if, still paused at the breakpoint at WriteLine, you execute Console.WriteLine(a4) from the immediate window, it will print an empty line to the console, as if a4 is indeed null at that point.

StackOverflow question for additional information: https://stackoverflow.com/q/62369934

貢獻者指南