Skip to content

C#: Add null-conditional (?.) support to CSharpPattern#6997

Merged
knutwannheden merged 1 commit intomainfrom
add-null-conditional-.-support-to-csharppattern
Mar 17, 2026
Merged

C#: Add null-conditional (?.) support to CSharpPattern#6997
knutwannheden merged 1 commit intomainfrom
add-null-conditional-.-support-to-csharppattern

Conversation

@knutwannheden
Copy link
Contributor

Summary

CSharpPattern could not distinguish between regular member access (.) and null-conditional member access (?.). This meant a pattern like {obj}?.ToString() would incorrectly match x.ToString(), and {obj}.ToString() would incorrectly match x?.ToString(). Recipe authors targeting null-conditional expressions had no way to be precise about which access style they wanted to match.

The root cause: PatternMatchingComparator skips all Markers during structural comparison, but ?. is represented as a NullSafe marker on the FieldAccess.Name / MethodInvocation.Name identifier — so the two forms were structurally identical to the comparator.

After this change, patterns correctly distinguish the two forms:

var obj = Capture.Of<Expression>("obj");

// Matches only x?.ToString(), not x.ToString()
var nullConditional = CSharpPattern.Create($"{obj}?.ToString()");

// Matches only x.ToString(), not x?.ToString()
var regular = CSharpPattern.Create($"{obj}.ToString()");

Changes

  • PatternMatchingComparator: Check NullSafe marker presence when comparing nodes. If the pattern node has a NullSafe marker, the candidate must too (and vice versa).
  • PatternMatchTests: 5 new tests covering null-conditional method calls, field access, exact matching, and negative cases for both directions (. pattern vs ?. candidate and ?. pattern vs . candidate).

Test plan

  • All 67 PatternMatchTests pass (62 existing + 5 new)
  • CI green

The pattern comparator skipped all Markers during structural matching,
making `?.` and `.` indistinguishable. Check for the NullSafe marker
so patterns like `{obj}?.ToString()` only match null-conditional access.
@github-project-automation github-project-automation bot moved this to In Progress in OpenRewrite Mar 17, 2026
@knutwannheden knutwannheden changed the title C#: Add null-conditional (?.) support to CSharpPattern C#: Add null-conditional (?.) support to CSharpPattern Mar 17, 2026
@knutwannheden knutwannheden merged commit e37b3e6 into main Mar 17, 2026
1 check passed
@knutwannheden knutwannheden deleted the add-null-conditional-.-support-to-csharppattern branch March 17, 2026 07:47
@github-project-automation github-project-automation bot moved this from In Progress to Done in OpenRewrite Mar 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant