Search code examples
c#.netvisual-studiorefactoringautomated-refactoring

Can I refactor class constructor to use a a new class, using Visual Studio?


I have the following class, that has too many parameters in the constructor, and I want to refactor the class to receive only one object that encapsulate all the parameters.

public class MyClass
{
    public MyClass(
       string param1,
       string param2,
       string param3,
       string param4,
       string param5)
    {
       ...
    }
}

Is it possible to use Visual Studio refactor utility to encapsulate all the constructor parameters in a new class?

public class MyClass
{
    public MyClass(MyClassParameters parameters)
    {
       ...
    }
}

public class MyClassParameters
{
    public string Param1 { get; set; }
    public string Param2 { get; set; }
    public string Param3 { get; set; }
    public string Param4 { get; set; }
    public string Param5 { get; set; }
}

So my questions are

  • Can I do this using Visual Studio, so I don't have to manually update all the refereces to class MyClass?
  • Are there other refactor tools that support this functionality, such as Resharper, or others?

It is a hard work, since I have thousands of references to this class in my unit testing suite.


Solution

  • Do you have ReSharper?
    With ReSharper you set cursor on constructor, press Ctrl+R, Ctrl+R and select Extract Class From Parameters....