Skip to main content

Declare Property with Initializer

  • 2 minutes to read

Purpose

Declares a property for a selected method parameter and initializes it. You can use this code provider for Test-Driven Development.

screencast

Declare Property with Initializer generates a property name based on the selected method parameter name.

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

Usage

  1. Place the caret in an undeclared method parameter.

    class TestClass
    {
        bool DeleteRecord (int ID)
        {
            //...
            return true;
        }
    }
    
  2. Press Ctrl + . or Ctrl +~ to invoke the Code Actions menu.

  3. Choose Declare Property with Initializer from the menu and press Enter.

    menu

    The red target picker marker appears. It allows you to choose the place where the generated code can be inserted.

    target-picker

    You can configure the Target Picker on the Editor | All Languages | Code Actions | Target Picker options page.

    target-picker-options

  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, this code provider adds the auto-implemented property to the current class and assigns the parameter value to it. This code provider also links a declared property and all its references. If you change any single property reference, CodeRush applies this change to other property references.

links

Blazor Support

The Declare Property with Initializer code provider is available from the @code section and markup of .razor files. The following screencast shows how to run this code provider from the @code section:

DeclarePropertyWith

Note

If a Razor code-behind file (.razor.cs) exists, the Declare Property with Initializer code provider adds the initialized property to this file instead of the @code section.

Customization

Change Scope

You can change the default visibility modifier of the generated property on the Editor | C# (Visual Basic) | Scope Options options page.

Options_Scope

For example, set the default scope for a declared property to “Private”. The Declare Property with Initializer provider creates a property with the private visibility, as shown below:

int ID { get; set; }

See the following topic for details: Scope.