0
void Main()
{
    var input1 = new ListNode(3);
    var input2 = new ListNode(4);
    
    var sum = input1?.Value??0 + input2?.Value??0;
    sum.Dump();
}

public class ListNode
{
    public ListNode(int value = 0, ListNode next = null)
    {
        Value = value;
        Next = next; 
    }
    public int Value;
    public ListNode Next;
}

In the above code
input1?.Value??0 evaluates to 3
and input2?.Value??0 evaluates to 4
but (input1?.Value??0 + input2?.Value??0) evaluates to 3

If I change the code to (input1?.Value??0) + (input2?.Value??0) I get the expected answer 7.

Can someone explain this behaviour? I think it's reasonable to expect a 7 or an error. Why do we get 3 as the answer?

gtestasker
  • 53
  • 7

0 Answers0