Improve langversion diagnostics for "unsafe in iterators" feature #80650
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
When using pointers in nested local functions inside iterators within unsafe classes, C# 12 reported a confusing diagnostic: "Feature 'ref and unsafe in async and iterator methods' is not available in C# 12.0". However, upgrading to C# 13 didn't fix the issue—instead, it showed "Pointers and fixed size buffers may only be used in an unsafe context". This created a misleading upgrade path.
Example:
Root Cause
The issue stems from how iterators handle unsafe contexts between C# versions:
When the compiler detected pointer usage in nested local functions, it saw:
But this was misleading because upgrading to C# 13 wouldn't help—the iterator would establish a safe context, requiring an explicit
unsafe
modifier on the local function.Solution
This PR fixes the diagnostic logic in two places:
InMethodBinder.IsIndirectlyInIterator
: Now correctly checks the parent binder chain for nested functions, ensuring we properly detect when code is indirectly within an iterator.Binder_Unsafe.GetUnsafeDiagnosticInfo
: Improved to reportERR_UnsafeNeeded
instead ofERR_FeatureNotAvailableInVersion12
when:unsafe
modifier)This provides users with the correct diagnostic in C# 12, matching what they'd see in C# 13, and clearly indicates that the solution is to add an
unsafe
modifier to the local function.After this fix
The fix ensures consistent, helpful error messages across language versions and correctly guides users to the proper solution.
Fixes #[issue-number-from-original-issue]
Original prompt
Fixes #73280
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.