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

Offen

#45.165 geöffnet am 14.06.2020

 (3 Kommentare) (1 Reaktion) (1 zugewiesene Person)C# (4.257 Forks)batch import
Area-InteractiveBugInteractive-Debugginghelp wanted

Repository-Metriken

Stars
 (20.414 Sterne)
PR-Merge-Metriken
 (Durchschn. Merge 6T 17h) (256 gemergte PRs in 30 T)

Beschreibung

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

Contributor Guide