Back to Devexpress

Declare Constant

coderushforroslyn-115697-coding-assistance-code-providers-declaration-providers-declare-constant.md

latest3.1 KB
Original Source

Declare Constant

  • Aug 25, 2021
  • 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

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

  2. Press Ctrl + . or Ctrl + ~ to invoke the Code Actions 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.

  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.

csharp
class TestClass
{
   public bool Test()
   {
      //...
      Console.WriteLine("[ERROR]" + STR_Failed);
      return false;
   }
   const string STR_Failed = "The test has failed.";
}
vb
Class TestClass
    Public Function Test() As Boolean
        Console.WriteLine("[ERROR]" & STR_TheTestHasBeenFailed)
        Return False
    End Function

    Const STR_TheTestHasBeenFailed As String = "The test has failed."
End Class

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:

csharp
public const string STR_Failed = "The test has failed.";
vb
Public Const STR_TheTestHasBeenFailed As String = "The test has failed."

See the following topic for details: Scope.