Reputation: 12077
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);
}
Upvotes: 0
Views: 90
Reputation: 223277
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....
Upvotes: 4