Declare Field with Initializer
- 3 minutes to read
Purpose
Generates a field and initializes it with the selected parameter. This code provider determines the field type based on the selected method parameter.
This code provider also links the declared field and all its references. If you change a field reference (“iD” in this example), CodeRush applies this change to other field references.
Declare Field with Initializer generates a field name based on the selected method parameter name and naming convention settings specified for this field. Refer to the following section for information about naming convention customization: Configure Naming Conventions.
This provider can also drop a marker onto the selected method parameter, 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 method parameter within the method declaration.
Usage
Place the caret in an undeclared parameter.
Press Ctrl + . or Ctrl + ~ to invoke the Code Actions menu.
Select Declare Field with Initializer from the menu and press Enter. A red target picker marker appears. This marker allows you to choose the place where this code provider can insert the generated code.
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, this code provider adds the initialized field declaration to the current class and assigns the parameter value to it.
Blazor Support
The Declare Field with Initializer 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 adds the declared field to this file instead of the @code section.
Customization
Configure Naming Conventions
You can configure naming convention settings for private and non-private fields on the Editor | <Language> | Naming Conventions options page.
For example, to change naming conventions for private fields, configure the naming convention’s main rule for “Instance Private Fields”. See the corresponding section of the “Naming Conventions” topic for details: Naming Conventions: Configure Main Rule.
Run the Declare Field with Initializer code provider to apply the naming convention’s main rule:
namespace App
{
public class MyClass
{
public MyClass(int firstParameter)
{
}
}
}
This code provider declares the “_FirstParameter” field that matches the naming convention’s main rule.
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 with Initializer provider creates a field with the public visibility, as shown below:
See the following topic for details: Scope.