Declare Constant
- 3 minutes to read
Purpose
Creates a constant from a literal. This code provider also links a declared constant and all its references. If you change any single constant reference, CodeRush applies this change to other constant references.
The Declare Constant provider can drop a marker onto the created constant reference, if the Marker feature is enabled. See the following topic section for more details: Markers: How to Enable.
Availability
Available when the caret is in a literal.
Usage
Place the caret in a literal (“The test has failed.” in this example).
Press Ctrl + . or Ctrl + ~ to invoke the Code Actions menu.
Select Declare Constant from the menu and press Enter. A red target picker marker appears that allows you to choose the place where the generated code can be inserted.
You can configure the Target Picker on the Editor | All Languages | Code Actions | Target Picker options page.
Use the Up Arrow and Down Arrow keys to move the target picker.
Press Enter to generate a code in the selected place.
After execution, the code provider creates a constant of the corresponding type and assigns a literal value to it.
class TestClass
{
public bool Test()
{
//...
Console.WriteLine("[ERROR]" + STR_Failed);
return false;
}
const string STR_Failed = "The test has failed.";
}
Blazor Support
The Declare Constant code provider is available from the @code section and markup of .razor files:
Note
If a Razor code-behind file (.razor.cs) exists, this code provider applied from Razor markup adds the constant to it instead of the @code section.
Customization
Change Scope
You can change the default visibility modifier of the generated constant on the Editor | C# (Visual Basic) | Scope Options options page.
For example, set the default scope for a declared constant to “Public”. The Declare Constant provider creates a constant with the public visibility, as shown below:
See the following topic for details: Scope.