Skip to main content

Extract Interface

  • 2 minutes to read

Extracts an interface of public members from a class.

#Purpose

This refactoring is great as a first step to changing your code, so that it uses interfaces instead of specific classes. It allows you to create a new interface based on the class you used previously, and makes that class implement that interface.

#Availability

Available from the context menu or via shortcuts:

  • when the caret is on a class declaration statement. The caret should be on the class name and the class should have at least one public member.

#Notes

  • The resulting interface is declared right above the source class.
  • Rename is automatically invoked for the newly declared interface.

#Example

class ProductInfo
{
    private int _unitPrice;
    private int _count;
    private int _UnitPrice;
    public int UnitPrice
    {
        get { return _UnitPrice; }
        set { _UnitPrice = value; }
    }
    public int Count
    {
        get { return _count; }
        set { _count = value; }
    }
}
Public Class ProductInfo
    Private _unitPrice As Integer
    Private _count As Integer
    Public Property unitPrice() As Integer
        Get
            Return _unitPrice
        End Get
        Set(ByVal value As Integer)
            _unitPrice = value
        End Set
    End Property
    Public Property count() As Integer
        Get
            Return _count
        End Get
        Set(ByVal value As Integer)
            _count = value
        End Set
    End Property
End Class

Result:

internal interface MyInterface
{
    int UnitPrice { get; set; }
    int Count { get; set; }
}
class ProductInfo : IProductInfo
{
    private int _unitPrice;
    private int _count;
    private int _UnitPrice;
    public int UnitPrice
    {
        get { return _UnitPrice; }
        set { _UnitPrice = value; }
    }
    public int Count
    {
        get { return _count; }
        set { _count = value; }
    }
}
Public Interface MyInterface
    Property unitPrice() As Integer
    Property count() As Integer
End Interface
Public Class ProductInfo
    Implements MyInterface
    Private _unitPrice As Integer
    Private _count As Integer
    Public Property unitPrice() As Integer Implements MyInterface.unitPrice
        Get
            Return _unitPrice
        End Get
        Set(ByVal value As Integer)
            _unitPrice = value
        End Set
    End Property
    Public Property count() As Integer Implements MyInterface.count
        Get
            Return _count
        End Get
        Set(ByVal value As Integer)
            _count = value
        End Set
    End Property
End Class

#Animation

rsExtractInterfaceCSharp