Why does this code throw an ArgumentNullException
?
string text = null;
var x = text?.Split('#');
var y = x.ElementAtOrDefault(1);
but this code does not:
string text = null;
var z = text?.Split('#').ElementAtOrDefault(1);
To get the first snippet to work, I have to use null propagation operator (?
) on x
:
string text = null;
var x = text?.Split('#');
var y = x?.ElementAtOrDefault(1);
but in the second, it's not required:
var z = text?.Split('#').ElementAtOrDefault(1);
Why?
It's because of how the expressions are evaluated:
string text = null; // text is null
var x = text?.Split('#'); // x is null
var y = x.ElementAtOrDefault(1); // null.ElementAtOrDefault throws an NRE
with your other example:
string text = null; // text is null
var z = text?.Split('#').ElementAtOrDefault(1); // z is null, nothing past ?. is evaluated because text was null
Fundamentally, the null propagation operator converts this:
Something?.SomethingElse(...)
To this ternary operation:
Something == null ? null : Something.SomethingElse(...)
And so the execution past the ?.
operator is short-circuited out (not executed) when the variable is null
.