Daniel Peñalba
Daniel Peñalba

Reputation: 31887

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

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

Upvotes: 0

Views: 657

Answers (3)

SPFiredrake
SPFiredrake

Reputation: 3892

If the class is being used all over the place already, what you can do is just create another constructor taking the MyParameter parameter, copy over the old functionality (updating the references to each parameter to the MyParameter properties/fields), and just have the old constructor read:

public MyClass(
   string param1,
   string param2,
   string param3,
   string param4,
   string param5) : this(new MyParameter(param1, param2...))
{
}

Not the prettiest solution, but as Oded mentions, there's no "built-in" way to refactor constructor parameters.

Upvotes: 0

brgerner
brgerner

Reputation: 4371

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

Upvotes: 3

Oded
Oded

Reputation: 499212

The built in C# refactoring options do not include the "introduce parameter object" refactoring.

Resharper and Refactor Pro (both commercial) do have it.

Upvotes: 4

Related Questions