Extract Interface
- 3 minutes to read
Extracts an interface from public members of a class.
You can use this refactoring in C# projects that contain file-scoped namespace declarations.
Purpose
This refactoring allows you to create a new interface based on a selected class. It also makes this class implement this interface.
Availability
Available when the caret is in a class declaration statement. The caret should be in a class name and the class should contain at least one public member.
Usage
Place the caret in a class declaration. For example, in the “ProductInfo” class.
Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu. Select Extract Interface from the menu and press Enter.
The Extract Interface refactoring creates a new interface based on the selected class, moves this interface to a new file named after this type (IProductInfo.cs, in this example), and makes the original class to implement the interface. This refactoring also runs the Rename refactoring.
Note
You can configure whether CodeRush opens a generated file when it applies this refactoring. CodeRush also allows you to change the position of the newly-generated interface in code (the generated interface can be placed above or below the active type). For more information, refer to the following topic: Code Actions Settings.
In the code editor, you can type a new name for the generated interface or leave it as is. Press Enter in the code editor or click Apply in the Rename hint to apply the changes and close the hint.
The following code shows the result:
//FileName: ProductInfo.cs
using System;
namespace MyApp
{
class ProductInfo : IProductInfo
{
private int unitPrice;
private int count;
public int UnitPrice {
get { return unitPrice; }
set { unitPrice = value; }
}
public int Count {
get { return count; }
set { count = value; }
}
}
}