ReSharper Help  

Replace Constructor with Factory Method

The Replace Constructor with Factory Method refactoring allows you to "encapsulate" a constructor with a static method which 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. Subclasses can then override it to specify the derived type of object that will be created.

Consider the following example.

 

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

As a result, calls to the constructor, such as shown below:

...are replaced with calls to the new factory method:

To replace a constructor with a factory method

  1. In the editor, place the caret at the name of the symbol to be deleted.
  2. Do one of the following:
    • On the main menu, click ReSharper | Refactor | Replace Constructor with Factory Method.
    • Right-click the method name and select Refactor | Replace Constructor with Factory Method in the context menu.
    • Press Ctrl + Shift + R, and then select Replace Constructor with Factory Method.

    The Replace Constructor with Factory Method dialog box opens.

  3. Type the factory method name.
  4. Specify the fully qualified name of the class.
  5. Click Continue. If no conflicts are found, the refactoring is applied immediately.

See Also

Refactoring Code