Skip to main content

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.

DeclareConstant

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

  1. Place the caret in a literal (“The test has failed.” in this example).

    class TestClass
    {
       public bool Test()
       {
          //...
          Console.WriteLine("[ERROR]" + "The test has failed.");
          return false;
       }    
    }
    
  2. Press Ctrl + . or Ctrl + ~ to invoke the Code Actions menu.

    declare-provider-menu

  3. 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.

    declare-provider-target-picker

    You can configure the Target Picker on the Editor | All Languages | Code Actions | Target Picker options page.

    TargetPicker

  4. Use the Up Arrow and Down Arrow keys to move the target picker.

  5. 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:

Blazor Declare Constant

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.

Options_Scope

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:

public const string STR_Failed = "The test has failed.";

See the following topic for details: Scope.