coderushforroslyn-115702-coding-assistance-code-providers-declaration-providers-declare-method.md
Generates a method with appropriate parameters for an undeclared method call. You can use this code provider in Test-Driven Development.
The Declare Method provider adds a method declared in the interface to all its implementers.
This provider can also drop a marker onto the method call 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 method.
Place the caret in an undeclared method’s name (“GetCurrencyRate” in this example).
Press Ctrl + . or Ctrl + ~ to invoke the Code Actions menu.
Select Declare Method 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, this code provider adds the method declaration to the class/interface. In the example below, the Declare Method provider added the not-implemented GetCurrencyRate () method to the Sample class:
public class Sample
{
public static double ConvertToUSD(double amount, object source)
{
return amount / GetCurrencyRate(source);
}
static void Main(string[] args)
{
double price = ConvertToUSD(10, null);
}
static double GetCurrencyRate(object source)
{
throw new NotImplementedException();
}
}
Class Sample
Public Shared Function ConvertToUSD(amount As Double, source As Object) As Double
Return amount / GetCurrencyRate(source)
End Function
Shared Sub Main(ByVal args() As String)
Dim price As Double = ConvertToUSD(10, Nothing)
End Sub
Private Shared Function GetCurrencyRate(ByVal source As Object) As Double
Throw New NotImplementedException
End Function
End Class
The Declare Method code provider is available from the @code section and markup of .razor files:
Note
If a Razor code-behind file (.razor.cs) exists, the Declare Method code provider adds the declared method to this file instead of the @code section.
You can configure the default body of newly-generated methods on the Editor | C# (Visual Basic)| Code Actions | Code Actions Settings options page. The default value is “Throw NotImplementedException instance”.
Refer to the following topic for more information: Code Actions Settings.
You can change the default visibility modifier of a declared method on the Editor | C# (Visual Basic) | Scope Options options page.
For example, set the default scope for this method to “Protected”. The code provider declares a method with the protected visibility, as shown below:
protected static double GetCurrencyRate(object source)
{
throw new NotImplementedException();
}
Protected Shared Function GetCurrencyRate(ByVal source As Object) As Double
Throw New NotImplementedException
End Function
See the following topic for details: Scope.