ReSharper 8.0 Web Help

The Replace Constructor with Factory Method refactoring allows you to encapsulate a constructor with a static method that returns a new instance of a class.

The Factory Method pattern is a way of creating objects without specifying the exact class of object that will be created. A separate method for creating the objects is generated.

To replace a constructor with a factory method
  1. In the editor, place the caret at a constructor.
  2. Do one of the following:
    • On the main menu, choose ReSharper | Refactor | Replace Constructor with Factory Method.
    • Choose Refactor | Replace Constructor with Factory Method on the context menu.
    • Press Ctrl+Shift+RCtrl+Shift+R, then click Replace Constructor with Factory Method.
  3. The Replace Constructor with Factory Method dialog box opens. Enter a name for a new factory method in the Factory method name text box.

    Refactorings__Replace_Constructor_with_Factory_Method__dialog_box

  4. In the In class drop-down list, specify the fully qualified name of the class that the factory method should instantiate.
  5. Click Next. If no conflicts are found, the refactoring is applied immediately. Otherwise, resolve conflicts.

Consider the following example:

Refactorings__Replace_Constructor_with_Factory_Method__code__before

After replacing this public constructor with a factory method, the constructor is made private, and a new static factory method is introduced that calls the constructor:

Refactorings__Replace_Constructor_with_Factory_Method__code__after

Existing calls to the constructor are replaced with calls to the new factory method.


This feature is supported in the following languages/technologies:

C# VB.NET HTML ASPX Razor JavaScript TypeScript CSS XML XAML RESX Build Scripts
feature_available feature_available

Tip

The instructions and examples given here address the use of the feature in C#. For details specific to other languages, see the corresponding topics in the ReSharper by Language section.