coderushforroslyn-115731-coding-assistance-code-providers-declaration-providers-declare-field.md
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.
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.
Available when the caret is in an undeclared variable reference.
Place the caret in an undeclared variable (“testFailedText” in this example).
Press Ctrl + . or Ctrl + ~ to invoke the Code Actions menu.
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.
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, 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;
}
Class TestClass
Public Function Test() As Boolean
Console.WriteLine("[ERROR]" & testFailedText)
Return False
End Function
Dim testFailedText As String
End Class
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:
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.
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 provider creates a field with the public visibility, as shown below:
public string testFailedText;
Public testFailedText As String
See the following topic for details: Scope.