Creating a CodeRefactoringProvider to refactor source code to recommend using C# 7.0 tuples

Code refactoring providers are IDE extensions to refactor source code for better code structuring, without affecting the functional or semantic behavior of the code. These are built on top of Roslyn's Workspaces layer and operate on the current document being edited. When a user invokes a command such as Ctrl + dot in Visual Studio editor, the IDE code refactoring engine computes all the refactorings that can refactor the code in the currently selected text span in the editor. Each of these providers are then invoked with a code refactoring context containing the current document and span. Refactorings operate on the underlying syntax tree associated with the document by adding, removing, or editing the syntax nodes within the tree and returning the new document with the refactored code. They might also alter the contents of the containing project or solution. When the user commits the refactoring by pressing the Enter key, the code refactoring engine applies this refactoring to the user code.

In this section, we will write a CodeRefactoringProvider to propose the usage of tuple expressions, a C# 7.0 feature, in methods returning more than one value. Prior to C# 7.0, methods that wanted to return more than one value had the following possible implementations:

  1. Declare a non-void return type of one of the return values and out parameters for the remaining returned values.
  2. Declare a void return type and out parameters for each of the returned values.
  3. Declare a new type wrapping these values as fields, and return an instance of that type.

With C# 7.0, the recommended implementation is to declare a tuple return type with elements defined for types of each of the returned values and have no out parameters. We will write a refactoring to identify the existing code with pattern 1 earlier and recommend a refactoring to use tuples. For example, consider the following methods returning multiple return values:

private int MethodReturningTwoValues(out int x)
{
x = 0;
return 0;
}

private int MethodReturningThreeValues(out int x, int y, out int z)
{
x = 0;
z = 1;
return y;
}

Our code refactoring will offer to convert these methods to:

private (int, int) MethodReturningTwoValues()
{
int x;
x = 0;
return (0, x);
}

private (int, int, int) MethodReturningThreeValues(int y)
{
int x;
int z;
x = 0;
z = 1;
return (y, x, z);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset