Back to Devexpress

Extract Interface

coderushforroslyn-117650-refactoring-assistance-extract-interface.md

latest2.5 KB
Original Source

Extract Interface

  • Dec 13, 2021
  • 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

  1. Place the caret in a class declaration. For example, in the “ProductInfo” class.

  2. Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu. Select Extract Interface from the menu and press Enter.

  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:

csharp
//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; }
        }
    }
}
vb
'FileName: ProductInfo.vb
Public Class ProductInfo
    Implements IProductInfo

    Private _unitPrice As Integer
    Private _count As Integer
    Public Property unitPrice() As Integer Implements IProductInfo.unitPrice
        Get
            Return _unitPrice
        End Get
        Set(ByVal value As Integer)
            _unitPrice = value
        End Set
    End Property
    Public Property count() As Integer Implements IProductInfo.count
        Get
            Return _count
        End Get
        Set(ByVal value As Integer)
            _count = value
        End Set
    End Property
End Class
csharp
//FileName: IProductInfo.cs
namespace MyApp
{
    public interface IProductInfo
    {
        int Count { get; set; }
        int UnitPrice { get; set; }
    }
}
vb
'FileName: IProductInfo.vb
Public Interface IProductInfo
    Property count() As Integer
    Property unitPrice() As Integer
End Interface