Why are we allowed to use a parameter defined by an "is" expression in the else clause of a conditional operator?
Example:
int a = 3; int b = 4; int result = (a + b) is int sum && sum < 100 ? sum : sum - 1;
The expression sum - 1
is valid, and sum is still in scope, even though it’s in the else condition. Why is that so? I take it that if the is
expression returns false, sum would bear its default value, which for int
is 0
?
It seems that the compiler can prove that a + b
is always an int
, and so it knows that the is int
test will always be run, and will always pass. Therefore it knows that sum
is always assigned, regardless of what happens during the rest of the condition.
Try using something that might not be an int
, and see that you get an error:
int a = 3; int b = 4; object sumObject = a + b; // error CS0165: Use of unassigned local variable 'sum' int result = sumObject is int sum && sum < 100 ? sum : sum - 1;
Alternatively, you can do something like this, which also means that sum
might not always be assigned:
int a = 3; int b = 4; // error CS0165: Use of unassigned local variable 'sum' int result = false && (a + b) is int sum && sum < 100 ? sum : sum - 1;