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

Open

#45,165 opened on Jun 14, 2020

View on GitHub
 (3 comments) (1 reaction) (1 assignee)C# (20,414 stars) (4,257 forks)batch import
Area-InteractiveBugInteractive-Debugginghelp wanted

Description

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