Skip to main content

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.

Declare Field Menu

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

  1. Place the caret in an undeclared variable (“testFailedText” in this example).

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

    declare-field-menu

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

    red-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 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:

Declare Field Menu

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.

Options_Scope

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:

public string testFailedText;

See the following topic for details: Scope.