ReSharper
 
2024.3
Get ReSharper

Replace Constructor with Factory Method refactoring

Last modified: 30 July 2024

This refactoring helps implement the factory method pattern for an existing class. If you opt to create the factory method in the same class, the refactoring makes the selected constructor private and encapsulates it into a static method that returns a new instance of the class. You can also choose to create the factory method in any other class. In this case, the constructor stays public, you can change its access modifier later, if necessary.

If there are any usages of the constructor, they are replaced with factory method calls.

In the example below, we use the refactoring to add the factory method in the same class:

ReSharper. Replace Constructor with Factory Method refactoring

This feature is supported in the following languages and technologies:

The instructions and examples given here address the use of the feature in C#. For more information about other languages, refer to corresponding topics in the Languages and frameworks section.