Extract Interface

  • 3 minutes to read

Extracts an interface from public members of a class.

Purpose

This refactoring allows you to create a new interface based on a selected class. It also makes this class to 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

  1. Place the caret in a class declaration.

    NOTE

    The blinking cursor shows the caret's position at which the Refactoring is available.

    class ProductInfo
    {
        private int unitPrice;
        private int count;
    
        public int UnitPrice {
            get { return unitPrice; }
            set { unitPrice = value; }
        }
        public int Count {
            get { return count; }
            set { count = value; }
        }
    }
    
  2. 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.

    Invoke

    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.

  3. 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; }
        }
    }
}
//FileName: IProductInfo.cs
namespace MyApp
{
    public interface IProductInfo
    {
        int Count { get; set; }
        int UnitPrice { get; set; }
    }
}