Home > Refactorings > Refactorings – Make Extension Method

Refactorings – Make Extension Method

October 31st, 2011

The Make Extension refactoring converts a regular method into an extension method based on the selected parameter type. Extension methods allow you to extend an existing type, including classes, structures or interfaces, with the new functionality, without having to derive from that class and without modifying the code of the type itself. The extended type is taken from the parameter that you choose when applying the refactoring.

Extension methods must be declared inside the static classes, so the refactoring allows you to create a new static class called Extensions:

Refactor! Make Extension to a new Class

or choose an existing static class via the sub menu:

Refactor! Make Extension to existing class

The refactoring is available on the method’s signature from its start to the end of its name. All calling sides are automatically updated once it is applied, so the created extension method is called on the corresponding argument passed to the source method.

If you choose an existing static class and move a method there, you can choose a target location using the Target Picker inside the chosen class. If you are going to create a new static class, then you can choose a location of that class.

The Make Extension refactoring is useful to extend existing types when you see a functionality that you tend to think might be a good addition to an existing class. Consider the System.String class and the following regular method:

public int GetWhiteSpaceCount(string text)
{
  int result = 0;
  if (String.IsNullOrEmpty(text))
    return result;

  foreach (char item in text)
    if (Char.IsWhiteSpace(item))
      result++;

  return result;
}

This method calculates and returns the count of whitespace characters in the given string. Instead of referencing this method from a certain class (e.g. StringUtilities) you are able to easily convert it into an extension method and call it anywhere without referencing the type containing this method. The Make Extension refactoring will produce the following code for this method:

public static class Extensions
{
  public static int GetWhiteSpaceCount(this string text)
  {
    int result = 0;
    if (String.IsNullOrEmpty(text))
      return result;

    foreach (char item in text)
      if (Char.IsWhiteSpace(item))
        result++;

    return result;
  }
}

The method is now an extension of the System.String class and available on any reference of the String type, for example:

string data = GetData();
int whiteSpaceCount = data.GetWhiteSpaceCount();
—–
Products: Refactor! Pro
Versions: 11.1 and up
VS IDEs: any
Updated: Oct/31/2011
ID: R041

Similar Posts: