Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

How to: Refactor Code with Extract Method 

The following procedure describes how to create a new method from a code fragment of an existing member. Use this procedure to perform the Extract Method refactoring operation.

To use Extract Method

  1. Create a console application as described in the example below.

    For more information, see Console Application.

  2. In the Code Editor, select the code fragment you want to extract:

    double area = PI * radius * radius.
    
  3. Select Extract Method on the Refactor menu. The Extract Method Dialog Box appears.

    You can also type the keyboard shortcut CTRL+R, CTRL+M to display the Extract Method Dialog Box.

    You can also right-click the selected code, point to Refactor on the context menu, and then click Extract Method to display the Extract Method Dialog Box.

  4. Specify a name for the new method in the New Method Name text box such as CircleArea. A preview of the new method signature displays under Preview Method Signature.

  5. Click the OK button.

Example

To set up this example, create a console application named ExtractMethod, and then replace Class1 with the following code. For more information, see Console Application.

    class A
    {
        const double PI = 3.141592;

        double CalculatePaintNeeded(double paintPerUnit, double radius)
        {
            // Select any of the following:
            // 1. The entire next line of code.
            // 2. The right-hand side of the next line of code.
            // 3. Just "PI *" of the right-hand side of the next line
            //    of code (to see the prompt for selection expansion).
            // 4.  All code within the method body.
            // ...Then invoke Extract Method.

            double area = PI * radius * radius;

            return area / paintPerUnit;
        }
    }

See Also

Reference

Extract Method

Concepts

Refactoring

Community Additions

ADD
Show:
© 2015 Microsoft