Summary
Empty collection expressions [] immediately after ? in conditional (ternary) expressions are misparsed. The parser interprets cond? as a nullable type and [] as an array rank specifier, instead of recognizing the ternary operator.
Reproduction
var x = condition ? [] : list;
Expected: Parsed as conditional expression with empty collection expression as consequence
Actual: Parsed as nullable array type declaration condition?[] followed by errors
Analysis
The grammar has an ambiguity: when it sees identifier?[], it can mean either:
identifier ? [] : ... - ternary with empty collection expression
identifier?[] - nullable array type (like int?[])
The grammar currently prefers interpretation #2, causing parse errors when : follows.
What Works
Notably, non-empty collection expressions in ternaries parse correctly:
// These all work:
var a = []; // standalone empty collection
var b = [1, 2, 3]; // collection with elements
var c = [..list]; // spread operator
var d = cond ? [1] : list; // non-empty in ternary ✓
// This fails:
var e = cond ? [] : list; // empty in ternary ✗
The issue is specifically the token sequence ? [] where [] is empty.
Real-World Impact
This pattern appears in production code:
var items = shouldClear ? [] : existingItems;
var result = new Response {
Tags = includeAll
? [] // Parse error here
: FilterTags(input)
};
Possible Fix
The grammar may need disambiguation rules to prefer conditional_expression interpretation when ? is followed by [ ] : sequence.
Related
This is a specific edge case of the broader C# 12 collection expressions feature. See #401 for the general feature request, though most collection expression syntax already works.
Summary
Empty collection expressions
[]immediately after?in conditional (ternary) expressions are misparsed. The parser interpretscond?as a nullable type and[]as an array rank specifier, instead of recognizing the ternary operator.Reproduction
Expected: Parsed as conditional expression with empty collection expression as consequence
Actual: Parsed as nullable array type declaration
condition?[]followed by errorsAnalysis
The grammar has an ambiguity: when it sees
identifier?[], it can mean either:identifier ? [] : ...- ternary with empty collection expressionidentifier?[]- nullable array type (likeint?[])The grammar currently prefers interpretation #2, causing parse errors when
:follows.What Works
Notably, non-empty collection expressions in ternaries parse correctly:
The issue is specifically the token sequence
? []where[]is empty.Real-World Impact
This pattern appears in production code:
Possible Fix
The grammar may need disambiguation rules to prefer conditional_expression interpretation when
?is followed by[]:sequence.Related
This is a specific edge case of the broader C# 12 collection expressions feature. See #401 for the general feature request, though most collection expression syntax already works.