Declare Field
- 2 minutes to read
Purpose
Creates a field declaration for an undeclared reference. This code provider defines the field type based on the selected reference. You can use this code provider for Test-Driven Development.
The Declare Field provider can drop a marker onto the initial 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 an undeclared variable reference.
Usage
Place the caret in an undeclared variable (“testFailedText” in this example).
Press Ctrl + . or Ctrl + ~ to invoke the Code Actions menu.
Select Declare | Field 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 adds the field declaration to the current class and moves the caret to the field type.
class TestClass
{
public bool Test()
{
//...
Console.WriteLine("[ERROR]" + testFailedText);
return false;
}
string testFailedText;
}
Blazor Support
The Declare Field code provider is available from the @code section and markup of .razor files.
For example, run this provider from Razor markup to create a field for the active Blazor component:
Note
If a Razor code-behind file (.razor.cs) exists, this code provider adds the declared field to this file instead of the @code section.
Customization
Change Scope
You can change the default visibility modifier of the generated field on the Editor | C# (Visual Basic) | Scope Options options page.
For example, set the default scope for declared field to “Public”. The Declare Field provider creates a field with the public visibility, as shown below:
See the following topic for details: Scope.