roslyn icon indicating copy to clipboard operation
roslyn copied to clipboard

Add specific error for extension parameter usage in static members

Open Copilot opened this issue 2 weeks ago • 3 comments

Error CS9293 was too generic when extension parameters were referenced from static members, giving "Cannot use extension parameter in this context" without explaining the static/instance mismatch.

Changes

  • New error CS9347: "Static members cannot refer to extension parameter '{0}'. Use an instance member instead."
  • Modified Binder_Expressions.cs to detect static member context and emit the specific error with simplified logic using extracted boolean variables for clarity
  • Error message format: The parameter name is shown without its type (e.g., 'p' instead of 'int p') for conciseness
  • Preserved CS9293 for other invalid contexts (parameter defaults, attributes, nested types)
  • Updated 13 existing tests to expect the new error where applicable

Example

public static class Extensions
{
    extension(object o)
    {
        static object M() => o;  // Now: CS9347 (was: CS9293)
        void M2(int x = o) { }   // Still: CS9293 (correct context)
    }
}

Before: "Cannot use extension parameter 'object o' in this context."
After: "Static members cannot refer to extension parameter 'o'. Use an instance member instead."

Original prompt

The error message for using the extension parameter in a static extension method is confusing: today it just says "CS9293: Cannot use an extension parameter in this context". Please add a dedicated message just for this static/instance mismatch, with a message along the lines of "static extensions cannot refer to the extension parameter, use an instance method instead".


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot avatar Dec 09 '25 19:12 Copilot

@jcouv @jjonescz for another review please

333fred avatar Dec 11 '25 01:12 333fred

@333fred, @jcouv Not sure who assigned this work to copilot. Is there a specific GitHub issue that this PR is trying to address? #Closed

AlekseyTs avatar Dec 11 '25 20:12 AlekseyTs

Done with review pass (commit 8) #Closed

AlekseyTs avatar Dec 11 '25 20:12 AlekseyTs

Is there a specific GitHub issue that this PR is trying to address?

It was in response to a feedback tweet, not to a filed bug.

333fred avatar Dec 12 '25 17:12 333fred

@AlekseyTs @jcouv I reverted Binder_Extensions.cs to before this PR, then did the suggested splitting of the condition inside the existing check. I'm going to follow up with a simplification of the outer pattern after this PR.

333fred avatar Dec 12 '25 18:12 333fred

Done with review pass (commit 9) #Closed

AlekseyTs avatar Dec 12 '25 19:12 AlekseyTs