Promoting locals and constant value expressions into parameters
There are times when you realize that a local variable or a field reference within a method would be more useful if it was a parameter. Having a new parameter on a method will increase its flexibility for consumers. To convert the local variable, you should remove its declaration from the body of the method, add it as a parameter and replace all occurrences of a local to a new parameter. The same steps must be performed in the case of field references. Furthermore, all method references in the entire solution should be updated to pass a new value as an argument to a method with a new signature.
With the help of the Promote to Parameter refactoring, you can promote local variables, field references and any primitive values into parameters and make the required updates to the code automatically.
Choose a local variable, a field reference or a constant value and apply the refactoring to promote it into a parameter:
A field reference:
A local variable:
A constant value expression:
In every case, a new parameter is added and all calls to the method are updated as required. You can immediately rename a new parameter according to your preference.
A second version of the refactoring called Promote to Parameter (optional) behaves in absolutely the same manner as its original version. The difference between two refactorings is that the latter creates an optional parameter instead of the usual parameter:
Optional parameters provide default values within the member’s signature. So, if an argument is omitted from a call to that method, the default value will be used instead:
If we compare the Promote to Parameter refactoring to the Promote Local Variable to Parameter refactoring built-in to Visual Studio (VS refactoring), we see the following advantages of the refactoring shipped in CodeRush:
- The VS refactoring does not allow you to create optional parameters
- The VS refactoring can not be applied on the field reference within a method body
- The VS refactoring can not be applied on constant value expressions within a method body.