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+)

Aperta

#45.165 aperta il 14 giu 2020

 (3 commenti) (1 reazione) (1 assegnatario)C# (4257 fork)batch import
Area-InteractiveBugInteractive-Debugginghelp wanted

Metriche repository

Star
 (20.414 stelle)
Metriche merge PR
 (Merge medio 6g 17h) (256 PR mergiate in 30 g)

Descrizione

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

Guida contributor