Home > Code Generation > Declaring fields using CodeRush consume-first declaration features

Declaring fields using CodeRush consume-first declaration features

December 16th, 2011

Unlike the local variable declarations, fields are simply variables that are declared directly within the code block of a class or a structure. Fields are declared in the type block by specifying the access level of the field, the type of the field and the name of the field. A field may also include a readonly modifier. This type of field can only have its value set directly in its declaration or from within a constructor of its containing class.

With the help of CodeRush consume-first declaration features, you don’t have to type the definition of a field variable declaration by hand. Any reference to an undeclared element can be declared automatically for you in a single step. You can also declare a field variable and assign values of the method or constructor parameters. Here are useful code providers specific to field declarations:

  • Declare Field
  • Declare Field (read-only)
  • Declare Initialized Field
  • Declare Initialized Fields

Before you apply any of the code providers, you can see the resulting code that is being inserted.

The Declare Field code provider declares a new private field declaration from an undeclared reference inside the current type declaration:

CodeRush Declare Field preview

If there are several possible types, you can choose the type from a sub menu:

CodeRush Declare Field sub menus preview

The newly created declaration is placed near the other field declaration or at the top of the current type if there are no fields in the class or struct.

The Declare Field (read-only) allows you to declare a private read-only field declaration if the reference inside a constructor to an undeclared element that is not assigned:

CodeRush Declare Field (read-only) preview

The Declare Initialized Field and Declare Initialized Fields code providers both work with the parameters of a method or a constructor. They declare a field declaration and assign the value of a parameter to the newly created field declaration. The difference between these two code providers is that the Declare Initialized Field is available only for a single method parameter:

CodeRush Declare Initialized Field preview

and the Declare Initialized Fields allows you to declare fields for all parameters that are not yet assigned to any field when the editor caret is at the name of the method/constructor:

CodeRush Declare Initialized Fields preview

Both providers add linked identifiers that allow you to immediately rename the field declaration and the assignment reference. Also, a marker is dropped to be able to quickly navigate back to the starting source location.

See also: consume-first declaration features for local variables.

Products: CodeRush Pro, CodeRush Xpress
Versions: 11.2 and up
VS IDEs: any
Updated: Dec/16/2011
ID: C146

Similar Posts: