Denis
Denis

Reputation: 12077

:? 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);
        }

Upvotes: 0

Views: 90

Answers (1)

Habib
Habib

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....

enter image description here

Upvotes: 4

Related Questions