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

贡献者指南