Introduce Constant

Declares a new constant initialized to the value of the string or number under the edit cursor, or caret.

Introduce Constant is similar to Replace Magic Number with Symbolic Constant in Martin Fowler's Refactoring book. However, Introduce Constant works on strings in addition to numbers.

Purpose

It is better to have a single constant (with a good name which explains its purpose), than to have duplicate copies of a number or string scattered throughout your code. Constants allow you to easily change behavior by changing a single value in the code, instead of searching through code looking for each magic value to change.

Availability

Available from the context menu or via shortcuts:

  • when the edit cursor, or caret is on a number or string in the code.

Notes

  • You can choose the newly declared constant's location using the target picker (see Settings below).
  • After Introduce Constant, Rename is automatically activated so you can provide a meaningful name for the newly declared constant.
  • Introduce Constant optionally searches for the same strings or numbers used within the method body and continuously asks for your confirmation to replace the found string or number with a reference to the introduced constant. The replacer progress indicator is activated in this case. (See Settings below.)
  • To declare a new constant within the current method, use Introduce Constant (local) instead.

Options

  • You can choose the base name for a constant and customize the type-dependent prefixes that are used to construct the constant's name automatically.
  • You can choose the automatically assigned visibility / scope for the constant.
  • You can specify whether the newly introduced constant's declaration should be placed at the top of the current type, above the first use, inside the current method or within a specified region. There is also an option allowing you to choose the constant's position with the target picker.
  • You can specify if Introduce Constant should replace only the selected string or number, all the strings or numbers matching the selected one or only the constants you choose to replace. In the last case, the Replacer Progress Indicator is invoked to ask you for replacement confirmations.

Example

public int AddValue(int ValueA)
{
    return ValueA + 25;
}
Public Function AddValue(ByVal ValueA As Integer) As Integer
    Return ValueA + 25
End Function

Result:

private const int MyConst = 25;
public int AddValue(int ValueA)
{
    return ValueA + MyConst;
}
Private Const MyConst As Integer = 25
Public Function AddValue(ByVal ValueA As Integer) As Integer
    Return ValueA + MyConst
End Function

Animation

rsIntroduceConstant

See Also