Declare Local

  • 4 minutes to read

Purpose

Generates a local variable for an undeclared reference. This code provider defines the variable type based on the selected reference.

screencast

The Declare Local provider can drop a marker onto the local variable 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 a reference to an undeclared variable (“percentage” in this example).

    class Sample
    {
        double CalculateDiscount(double price)
        {
            double fraction = percentage / 100d;
            return price - fraction * price;
        }
    }
    
  2. Press Ctrl + . or Ctrl + ~ to invoke the Code Actions menu, select Declare | Local from the menu and press Enter.

    DeclareLocal

After execution, the code provider declares a new local variable of the appropriate type (the explicitly typed local variable in the C# example) and puts the caret on its initial value. The new local variable is set to 0.

class Sample
{
    double CalculateDiscount(double price)
    {
        double percentage = 0d;
        double fraction = percentage / 100d;
        return price - fraction * price;
    }
}

Blazor Support

The Declare Local code provider is available from the @code section of .razor files:

declare-local-blazor

Customization

Enable the Red Target Picker Marker

A red target picker marker is disabled for this code provider. This target picker allows you to choose the place where the generated local variable can be inserted.

red-picker

To enable the target picker marker for this code provider, open the Editor | All Languages | Code Actions | Target Picker options page and check the Declare Local check box.

TargetPicker

Configure the Local Declaration Code Style Rule

The Declare Local code provider can generate an explicitly or implicitly typed local variable for an undeclared reference according to the specified code style rule.

The “Local declaration style” setting is disabled on the Editor | C# | Programming Style page of the CodeRush options dialog:

UserInfo

You can use Visual Studio code ‘var’ preferences and the corresponding setting in the EditorConfig file to configure the local declaration code style in CodeRush:

UserInfo

For example, set the “Elsewhere” setting to Prefer ‘var’ in Visual Studio Code ‘var’ preferences and run the Declare Local provider. This provider creates an implicitly typed local variable for an undeclared reference, as shown below:

class Sample
{
    double CalculateDiscount(double price)
    {
        var percentage = 0d;
        double fraction = percentage / 100d;
        return price - fraction * price;
    }        
}

Refer to the following topic for more information about the local declaration code style rule: Programming Style Rules