coderushforroslyn-115697-coding-assistance-code-providers-declaration-providers-declare-constant.md
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.
Available when the caret is in a literal.
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.
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.";
}
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
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.
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:
public const string STR_Failed = "The test has failed.";
Public Const STR_TheTestHasBeenFailed As String = "The test has failed."
See the following topic for details: Scope.