Promote Local Variable to Parameter Refactoring (C#)

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

Promote Local Variable to Parameter is a Visual C# refactoring operation that provides an easy way to move a variable from a local usage to a method, indexer, or constructor parameter while updating the call sites correctly.

Perform the Promote Local Variable to Parameter operation by first positioning the cursor on the variable you want to promote. The statement declaring the variable must also assign a value or expression to the variable. When the cursor is in position, invoke the Promote Local Variable to Parameter operation by typing the keyboard shortcut CTRL+R, P, or by selecting the command from the shortcut menu.

When you invoke the Promote Local Variable to Parameter operation, the variable is added to the end of the parameter list for the member. Any calls to the modified member are immediately updated with the new parameter as the expression originally assigned to the variable, leaving the code so that it functions the same as before the variable promotion.

To promote a local variable to parameter

  1. Create a console application named PromoteLocal, and then add the following example code after the Program class in the PromoteLocal namespace.

    class ProtoA
    {
        public static void MethodB()
        {
            // Invoke on 'i'
            int i = 0;
        }
    }
    
    class ProtoC
    {
        void MethodD()
        {
            ProtoA.MethodB();
        }
    }
    
    
  2. Place the pointer next to i at its definition in MethodB.

  3. From the Refactor menu, select Promote Local Variable to Parameter.

    You can also type the keyboard shortcut CTRL+R, P to complete the refactoring operation.

    You can also right-click the pointer, point to Refactor on the context menu, and then click Promote Local Variable to Parameter to complete the refactoring operation.

    The MethodB should now have a parameter int i, and the call ProtoA.MethodB will now pass zero as a value.

This refactoring works best when the variable being promoted is assigned a constant value. The variable must be declared and initialized, not just a declaration or just an assignment.

Show: