Note to future visitors: This question was based on faulty repro code. The ?.
operator does indeed short circuit. You can close this browser tab now.
There are many sources on the web that claim that the null conditional operator (?.
) short circuits (e.g. http://www.informit.com/articles/article.aspx?p=2421572, search for "circuit"). I cannot detect any such thing:
static void Main()
{
var c = new C();
Console.WriteLine(c?.Inner?.Inner); //does not rely on short circuiting, works
Console.WriteLine(c?.Inner.Inner); //throws NullReferenceException
}
class C
{
public C Inner;
}
Here, the first line works because of the second ?.
. The second ?.
saw null as its first operand and therefore returned null as well. This is not short circuiting.
Apparently, the rest of the chain executes even if the null case was triggered. The chain is not aborted. To me, short circuiting means that the chain is aborted. MSDN claims this is the case but the code example does not demonstrate short circuiting:
//The last example demonstrates that the null-condition operators are short-circuiting
int? count = customers?[0]?.Orders?.Count();
// null if customers, the first customer, or Orders is null
Was this behavior ever changed during the C# 6 development cycle? That would explain the bad sources on the web. And why is there so much talk about short circuiting if it's not there? I might be misunderstanding something here.
This is not a duplicate because it's about whether the operator short circuits or not (answer: no, although the accepted answer does not say that). This candidate is about nullable booleans and otherwise unrelated.