Skip to content

"Extract Method" handles variables defined from pattern matching poorly #79489

@Meowtimer

Description

@Meowtimer

Version Used:
5.0.0-1.25319.11

Steps to Reproduce:

  1. Have some statements/expressions doing pattern matching and extracting variables
  2. Select said code and invoke extract method refactoring

Original code:

static void PatternMatchingUsage()
{
  var t = (1, 2);
  // selection start
  switch (t)
  {
    case (var x, 2):
      Console.WriteLine(x);
      break;
  }
  // selection end
}

Expected Behavior:

Extract method treats extracted variables as belonging to the scope they are extracted in and does not introduce out parameters, extra declarations etc.

Actual Behavior:

Extracted method has extra declaration of extracted variable.

static void PatternMatchingUsage()
{
  var t = (1, 2);
  NewMethod(t);
}

private static void NewMethod((int, int) t)
{
  int x;
  switch (t)
  {
    case (var x, 2) when x % 2 is 0:
      Console.WriteLine(x);
      break;
  }
}

With more involved examples Extract method might introduce out parameters which then also produce actual compiler errors, not just warnings of unused variable declarations like in the example.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-IDEhelp wantedThe issue is "up for grabs" - add a comment if you are interested in working on it

    Type

    Projects

    Status

    InQueue

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions