Denis Denis - 4 months ago 22
C# Question

:? Conditional Operator Unexpected Evaluation Behavior

Can someone explain why the following throws an ArgumentNullException:

static void Main(string[] args) {
IEnumerable<int> lst= null;
var msg = ",lst=" + lst!= null ? String.Join(",", lst) : "null";
Console.WriteLine(msg);
}


and this doesn't:

static void Main(string[] args) {
IEnumerable<int> lst= null;
var msg = ",lst=" + (lst!= null ? String.Join(",", lst) : "null");
Console.WriteLine(msg);
}

Answer

Because of the operator precedence Your first line of code

var msg = ",lst=" + lst!= null ? String.Join(",", lst) : "null";

is equivalent to

var msg = (",lst=" + lst) != null ? String.Join(",", lst) : "null";

And since lst is null it throws Argument Null Exception in String.Join

May be a good time to invest in Resharper, look at the warning....

enter image description here